![]() |
VOOZH | about |
You are given an array of non-negative integers and a target sum. Your task is to find a contiguous subarray whose sum is the maximum possible, while ensuring that it does not exceed the given target sum.
Note: The given array contains only non-negative integers.
Examples:
Input: arr[] = [1, 2, 3, 4, 5], sum = 11
Output: 10
Explanation: Subarray having maximum sum is [1, 2, 3, 4]
Input: arr[] = [2, 4, 6, 8, 10], sum = 7
Output: 6
Explanation: Subarray having maximum sum is [2, 4]or [6]
Table of Content
We can solve this problem by generating all substrings, comparing their sums with the given sum, and updating the answer accordingly.
17
The maximum sum subarray can be found using a sliding window approach. Start by adding elements to
curr_sumwhile it's less than the target sum. Ifcurr_sumexceeds the sum, remove elements from the start until it fits within the limit. (Note: This method works only for non-negative elements.)
17
Note: For an array containing positive, negative, and zero elements, we can use the prefix sum along with sets to efficiently find the solution. The worst-case time complexity for this approach is O(n log n).
For a detailed explanation, refer to the article Maximum Subarray Sum Less Than or Equal to K Using Set.