Open In App

Maximum sum subarray having sum less than or equal to given sum

Last Updated : 05 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
17 Likes
Like
Report

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]

[Naive Approach] - Generate all Subarrays - O(n^2) Time and O(1) Space

We can solve this problem by generating all substrings, comparing their sums with the given sum, and updating the answer accordingly.

C++
Java Python C# JavaScript

Output
17

[Expected Approach] - Using Sliding Window - O(n) Time and O(n) Space

The maximum sum subarray can be found using a sliding window approach. Start by adding elements to curr_sum while it's less than the target sum. If curr_sum exceeds the sum, remove elements from the start until it fits within the limit. (Note: This method works only for non-negative elements.)

C++
Java Python C# JavaScript

Output
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.

 


Article Tags :
Practice Tags :

Similar Reads