Summary
Let’s assume that we will define the static method splitArray in the Solution class. Three parameters are required by the method: an integer array arr, which represents the array of numbers to be split; an integer N, which indicates the array's size; and an integer K, which indicates the maximum number of subarrays that can be created after splitting.
Solution
class Solution { static int splitArray(int[] arr , int N, int K) { // code here int start=0; int end=0; for(int i=0;i<N;i++){ start=Math.max(start,arr[i]); end+=arr[i]; } int mid; while(start<end){ mid=start+(end-start)/2; int sum=0; int pieces=1; for(int val:arr){ if(sum+val>mid){ sum=val; pieces++; }else{ sum+=val; } } if(pieces>K){ start=mid+1; }else{ end=mid; }
} return end; } }; |
Explanation
Set the start and end variables to 0. The lower and upper bounds of the binary search range for the minimum largest sum will be represented by these variables.
Determine the maximum element (start) and the total sum of the elements (end) by iterating through the array arr.
Conduct a binary search in the interval [start, end].
Determine the current range's midpoint within the binary search loop.
Answered by:> >arnabsaha849
Credit:> >GeekforGeeks
Suggested blogs:
>How to detect whether the linked list has a loop using Java
>How to determine the number of valid groupings for a string using Java
>How to mock a constant value in Python?
>Creating a pivot table by 6 month interval rather than year
>How to Install mariaDB client efficiently inside docker?
>Can I call an API to find out the random seed in Python `hash()` function?
>How remove residual lines after merge two regions using Geopandas in python?