Maximum Sum of Subarray Close to K

Given an array, find the maximum sum of subarray close to k but not larger than k.

Java Solution

The solution to this problem is obvious when we draw the following diagram.

maximum-sum-of-subarray-close-to-k

public int getLargestSumCloseToK(int[] arr, int k){
    int sum=0;
    TreeSet<Integer> set = new TreeSet<Integer>();
    int result=Integer.MIN_VALUE;
    set.add(0);
 
    for(int i=0; i<arr.length; i++){
        sum=sum+arr[i];
 
        Integer ceiling = set.ceiling(sum-k);
        if(ceiling!=null){
            result = Math.max(result, sum-ceiling);        
        }
 
        set.add(sum);
    }
 
    return result;
}

4 thoughts on “Maximum Sum of Subarray Close to K”

  1. won’t handle negative numbers. So technically u r more than target sum but if there are -ve numbers there is a possibility that adding those negative numbers may bring the total sum < k but closest to k and thus may be our answer.

  2. No. Kadane’s algorithm gives the maximum sum so far as we iterate over the array. The maximum so far may not be the value we want here. For example, given k = 6 and array [3 1 5]. The expected result should be 6, but the Kadane’s algorithm gives 4. The problem is that Kadane’s algorithm targets the maximum value so far, so as long as the previous values are positive, the previous values will not be dropped during the iteration.

Leave a Comment