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;
}
Category >> Others  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • krishan

    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.

  • Himanshu Poddar

    Why would sliding window concept not work here?

  • Bonsai

    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.

  • ab

    Can’t this be solved by Kadane’s algorithm like you have solved in http://www.programcreek.com/2013/02/leetcode-maximum-subarray-java/ ?