File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ bool isPossible (vector<int >& arr ,int m, int mid)
2
+ {
3
+ int count = 1 ;
4
+ int subarray_sum = 0 ;
5
+ int n = arr.size ();
6
+
7
+ for ( int i=0 ; i<n; i++)
8
+ {
9
+ if (subarray_sum+arr[i]> mid){
10
+
11
+ ++count;
12
+ subarray_sum = arr[i];
13
+
14
+ if (count>m)
15
+ return false ;
16
+ }
17
+
18
+ else {
19
+ subarray_sum += arr[i];
20
+ }
21
+
22
+
23
+ }
24
+ return true ;
25
+
26
+ }
27
+
28
+
29
+ class Solution {
30
+ public:
31
+ int splitArray (vector<int >& nums, int m) {
32
+
33
+ // Using binary search w/ monotonic search space
34
+
35
+ int s = *max_element (nums.begin (), nums.end ());
36
+ int e = accumulate (nums.begin (), nums.end (), 0 );
37
+ int ans = INT_MAX;
38
+
39
+
40
+ while (s<=e)
41
+ {
42
+ int mid = (s+e)/2 ;
43
+
44
+ if (isPossible (nums,m,mid))
45
+ {
46
+ ans = min (mid,ans);
47
+ e = mid - 1 ;
48
+ }
49
+
50
+ else
51
+ s = mid+1 ;
52
+
53
+ }
54
+
55
+ return ans;
56
+
57
+ }
58
+ };
You can’t perform that action at this time.
0 commit comments