-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathSplit Array.java
More file actions
55 lines (42 loc) · 951 Bytes
/
Split Array.java
File metadata and controls
55 lines (42 loc) · 951 Bytes
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
public class SpiltArray {
public static void main(String args[]) {
int[] nums= {7,2,5,10,8};
int m=2;
int awt=spiltArray(nums,m);
System.out.println(awt);
}
public static int spiltArray(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 is with 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;//here start ==end
}
}