Solution In Java (With Comments) || Time Complexity : nlogn (Greedy Approach)
public int splitArray(int[] arr, int M) 
    {
        //finding range in which ans lies
        int s=0; 
        int e=0;
        int n = arr.length;     
        for (int i = 0; i < n; i++) 
        {
            //e is sum of all elements in array ,here assuming M=1
            e = e+arr[i]; 
            if(arr[i]>s)
            {
                //s is max element in array ,here assuming M=n;
                s = arr[i]; 
            }
        }
        
        if(M == 1)
        {
            return e;
        }
        if(M == n)
        {
            return s;
        }

        int ans = e; //just assuming, as ans is largest sum

        //Now Applying Binary Search in range [s,e]
        while(s<=e)
        {
            int mid = s + (e-s)/2; //might be possible ans

            int count = 1; // number of splits maked
            int sum = 0; // sum of subarrays

            for (int i = 0; i < n; i++) 
            {
                if(sum + arr[i] <= mid)
                {
                    sum = sum + arr[i];
                }
                else
                {
                    count++;
                    sum = arr[i];
                }
            }
            if(count <= M)
            {
                ans = Math.min(ans,mid); //Minimum Largest sum
                e = mid-1;
            }
            else // count > M
            {
                //to decrease count
                //as number of 'splits Decreases' , value of 'ans Increases'
                s = mid+1; 
            }
        }
        return ans;
    
    }
Comments (0)