forked from souvikg544/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSplitArrayLargestSum.java
More file actions
56 lines (43 loc) · 1.91 KB
/
SplitArrayLargestSum.java
File metadata and controls
56 lines (43 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Split Array Largest Sum
// URL: https://leetcode.com/problems/split-array-largest-sum/
package com.akshat;
public class SplitArrayLargestSum {
public static void main(String[] args) {
int[] nums = {7, 2, 5, 10, 8};
int m = 2;
System.out.println(splitArray(nums, m));
}
static int splitArray(int[] nums, int m) {
int start = 0;
int end = 0;
for (int i = 0; i < nums.length; i++) {
start = Math.max(start, nums[i]); // in the end of the loop this will contain the max item of the array
end += nums[i];
}
// binary search
while (start < end) {
// try for the middle as potential ans
int mid = start + (end - start) / 2;
// calculate how many pieces you can divide this in with this max sum
int sum = 0;
int pieces = 1;
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
if (sum + num > mid) {
// you cannot add this in this subarray, make new one
// say you add this num in new subarray, then sum = num
sum = num;
pieces++;
} else {
sum += num;
}
}
if (pieces > m) {
start = mid + 1;
} else {
end = mid;
}
}
return end; // here start == end
}
}