We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Constructive Algorithms
  4. New Year Chaos
  5. Discussions

New Year Chaos

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • mariogersbach
    4 years ago+ 0 comments

    There is a pretty simple solution using only a single for-loop.

    // Complete the minimumBribes function below.
    void minimumBribes(vector<int> q) {
        int totalBribes = 0;
        
        int expectedFirst = 1;
        int expectedSecond = 2;
        int expectedThird = 3;
        
        for (unsigned int i = 0; i < q.size(); ++i) {
            if (q[i] == expectedFirst) {
                expectedFirst = expectedSecond;
                expectedSecond = expectedThird;
                ++expectedThird;
            } else if (q[i] == expectedSecond) {
                ++totalBribes;
                expectedSecond = expectedThird;
                ++expectedThird;
            } else if (q[i] == expectedThird) {
                totalBribes += 2;
                ++expectedThird;
            } else {
                cout << "Too chaotic" << endl;
                return;
            }
        }
        
        cout << totalBribes << endl;
    }
    
    581|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature