MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / Solution

Class Solution

SplitArrayLargestSum.java:1–52  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Solution {
2
3 public boolean isCorrect(int mid,int nums[],int m,int n)
4 {
5 int sum=0;
6 int noOfSubarrays=0;
7 for(int i=0;i<n;i++)
8 {
9 if(nums[i]>mid) return false;
10 sum+=nums[i];
11 if(sum>mid)
12 {
13 // increment number of subarray
14 noOfSubarrays++;
15 // start a new subarray if required size is exceeded
16 sum=nums[i];
17 }
18 }
19 noOfSubarrays++;
20 if(noOfSubarrays<=m) return true;
21 return false;
22 }
23
24 public int splitArray(int[] nums, int m) {
25 int start=Integer.MIN_VALUE,end=0;
26 int n=nums.length;
27 // calculate min and max of the range
28 for(int i=0;i<n;i++)
29 {
30 start=Math.max(start,nums[i]);
31 end+=nums[i];
32 }
33 int result=0;
34 // apply binary search
35 int mid=0;
36 while(start<=end)
37 {
38 mid=(start+end)/2;
39 if(isCorrect(mid,nums,m,n))
40 {
41 // store as result and check if we can further minimize it
42 result=mid;
43 end=mid-1;
44 }
45 else
46 {
47 start=mid+1;
48 }
49 }
50 return result;
51 }
52}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected