- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Max Chunks To Make Sorted in C++
Suppose we gave an array arr that is a permutation of [0, 1, ..., arr.length - 1], we have to split the array into some number of "chunks" or partitions, and individually sort each partition. So after concatenating them, the result will be the sorted array. So if the array is like [1,0,2,3,4], then the output will be 4, as we can split into two partitions like [1, 0] and [2,3,4], but this can also be true that [1, 0], [2], [3], [4]. So this is the highest number of chunks possible, so output is 4.
What is the most number of chunks we could have made?
To solve this, we will follow these steps −
- ans := 0, minVal := inf, n := size of arr, and maxVal := -inf
- for i in range 0 to n
- maxVal := max of arr[i] and maxVal
- if maxVal = i, then increase ans by 1
- return ans
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int maxChunksToSorted(vector<int>& arr) { int ans = 0; int minVal = INT_MAX; int n = arr.size(); int maxVal = INT_MIN; for(int i = 0; i < n; i++){ maxVal = max(arr[i], maxVal); if(maxVal == i){ ans++; } } return ans; } }; main(){ Solution ob; vector<int> v = {1,0,2,3,4}; cout << (ob.maxChunksToSorted(v)); }
Input
[1,0,2,3,4]
Output
4
Advertisements