Skip to content

Commit 1fa033d

Browse files
committed
created 0410-split-array-largest-sum.java
1 parent 0617997 commit 1fa033d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public int splitArray(int[] nums, int k) {
3+
int start = 0;
4+
int end = 0;
5+
6+
for (int i = 0; i < nums.length; i++) {
7+
start = Math.max(start, nums[i]);
8+
end += nums[i];
9+
}
10+
11+
while (start < end) {
12+
int mid = start + (end - start) / 2;
13+
14+
// calculate how many pieces you can divide this in with this max sum
15+
int sum = 0;
16+
int pieces = 1;
17+
for(int num : nums) {
18+
if (sum + num > mid) {
19+
sum = num;
20+
pieces++;
21+
} else {
22+
sum += num;
23+
}
24+
}
25+
26+
if (pieces > k) {
27+
start = mid + 1;
28+
} else {
29+
end = mid;
30+
}
31+
32+
}
33+
return end; // here start == end
34+
}
35+
}

0 commit comments

Comments
 (0)