Collecting Numbers

You are given an array that contains each number between  exactly once. Your task is to collect the numbers from 1 to in increasing order.

On each round, you go through the array from left to right and collect as many numbers as possible. What will be the total number of rounds?

Example:

Input:  n = 5, arr = {4, 2, 1, 5, 3}
Output: 3

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int collectingNumbers(int nvector<int&arr)
{

    vector<boolused(n + 1);
    int ans = 0;
    for (int i = 0i < ni++)
    {
        int x = arr[i];
        ans += !used[x - 1];
        used[x] = true;
    }
    return ans;
}

int main()
{
    int n = 5;
    vector<intarr = {42153};

    cout << collectingNumbers(narr<< "\n";

    return 0;
}


No comments:

Post a Comment