Partition Array into Disjoint Intervals in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A, we have to partition it into two subarrays left and right such that −

  • Every element in left subarray is less than or equal to every element in right subarray.

  • left and right subarrays are non-empty.

  • left subarray has the smallest possible size.

We have to find the length of left after such a partitioning. It is guaranteed that such a partitioning exists.

So if the input is like [5,0,3,8,6], then the output will be 3, as left array will be [5,0,3] and right subarray will be [8,6].

To solve this, we will follow these steps −

  • n := size of A, create an array maxx of size n

  • minVal := last element of A

  • maxx[0] := A[0]

  • for i in range 1 to n – 1

    • maxx[i] := max of A[i] and A[i – 1]

  • ans := size of A – 1

  • for i in range n – 1 down to 1

    • minVal := minimum of minVal and A[i]

    • if minVal >= max[i – 1], then ans := i

  • return ans

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int partitionDisjoint(vector <int>& A) {
      int n = A.size();
      vector <int> maxx(n);
      int minVal = A[n - 1];
      maxx[0] = A[0];
      for(int i = 1; i < n; i++){
         maxx[i] = max(A[i], maxx[i - 1]);
      }
      int ans = A.size() - 1;
      for(int i = n - 1; i >= 1; i--){
         minVal = min(minVal, A[i]);
         if(minVal >= maxx[i - 1]){
            ans = i;
         }
      }
      return ans;
   }
};
main(){
   vector<int> v1 = {5,0,3,8,6};
   Solution ob;
   cout << (ob.partitionDisjoint(v1));
}

Input

[5,0,3,8,6]

Output

3
raja
Published on 10-Apr-2020 13:36:13
Advertisements