Here's a naive algorithm that works in O (n²).
std::array<int, 3> input = {2, 2, -1}; int k = -1; int sum = 0, largestSum = *std::min_element(input.begin(), input.end()) -1; int i = 0, j = 0; int start = 0, end = 0; while (largestSum != k && i != input.size()) { sum += input[j]; if (sum <= k && sum > largestSum) { largestSum = sum; start = i; end = j; } ++j; if (j == input.size()) { ++i; j = i; sum = 0; } }
This is C ++, but it should not be difficult to write in Java or Javascript. He basically tries every possible sum (there is n*(n+1)/2 ) and stops if he finds k.
largestSum must be initialized to a low value. Since the smallest input element could be k, I subtracted 1 to it.
start and end are the first and last indices of the final subarray.
Of course, it could be improved if you had restrictions on the input data.
Living example
source share