Maximum Sum of Subarray Close to K

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

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


Java Solution

public int getLargestSumCloseToK(int[] arr, int k){
    int sum=0;
    TreeSet<Integer> set = new TreeSet<Integer>();
    int result=Integer.MIN_VALUE;
    for(int i=0; i<arr.length; i++){
        Integer ceiling = set.ceiling(sum-k);
            result = Math.max(result, sum-ceiling);        
    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:
String foo = "bar";

  1. ab on 2016-10-6

    Can’t this be solved by Kadane’s algorithm like you have solved in ?

Leave a comment