-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSplitArrayLargestSum.java
79 lines (73 loc) · 2.57 KB
/
SplitArrayLargestSum.java
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//https://leetcode.com/problems/split-array-largest-sum/description/
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 from the array
end+=nums[i];
}
//binary search
while(start<=end){
//try for the middle for the potential answer
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 num:nums){
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;
}
}
// Solution
// class Solution {
// public 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]); // max item from the array
// end += nums[i]; // total sum of all items in the array
// }
// // Binary search
// while (start < end) { // Use '<' instead of '<=' for proper narrowing of search space
// int mid = start + (end - start) / 2;
// int sum = 0;
// int pieces = 1;
// for (int num : nums) {
// if (sum + num > mid) {
// // cannot add this num to the current subarray, make a new subarray
// sum = num;
// pieces++;
// } else {
// sum += num;
// }
// }
// if (pieces > m) {
// start = mid + 1; // We need a larger sum since pieces are too many
// } else {
// end = mid; // We can try to reduce the sum
// }
// }
// return start; // start will be the minimal maximum sum when the loop ends
// }
//}