Divide Array in Sets of K Consecutive Numbers

Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers
Return True if it is possible. Otherwise, return False.

Example :

Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].

Approach:

C++

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

bool isPossibleDivide(vector<int&numsint k)
{
    //sort the array
    sort(nums.begin(), nums.end());
    priority_queue<pair<intint>, vector<pair<intint>>, 
greater<pair<intint>>> pq;

    //iterate for all the elements of the
    //array
    for (int num : nums)
    {
        while (!pq.empty() && (pq.top().first < num - 1 
|| pq.top().second == k))
        {
            if (pq.top().second != k)
            {
                return false;
            }

            pq.pop();
        }

        if (pq.empty() || pq.top().first == num)
        {
            pq.push(make_pair(num1));
            continue;
        }

        int size = pq.top().second + 1;
        pq.pop();
        pq.push(make_pair(numsize));
    }

    while (!pq.empty())
    {
        if (pq.top().second != k)
        {
            return false;
        }

        pq.pop();
    }

    return true;
}
int main()
{
    vector<intnums = {12334456};
    int k = 4;

    if (isPossibleDivide(numsk))
        cout << "true";
    else
        cout << "false";

    return 0;
}


No comments:

Post a Comment