Related Articles

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

• Difficulty Level : Medium
• Last Updated : 19 Jul, 2021

Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array.

(Note: Given array contains only non-negative integers.)

Examples:

```Input : arr[] = { 1, 2, 3, 4, 5 }
sum = 11
Output : 10
Subarray having maximum sum is { 1, 2, 3, 4 }

Input : arr[] = { 2, 4, 6, 8, 10 }
sum = 7
Output : 6
Subarray having maximum sum is { 2, 4 } or { 6 }```

Naive Approach: We can find the maximum sum of the subarray by running two loops. But the time complexity will be O(N*N).

Efficient Approach: The subarray having maximum sum can be found by using a sliding window. If curr_sum is less than sum include array elements to it. If it becomes greater than sum removes elements from start in curr_sum.  (This will work only in the case of non-negative elements.)

## C++

 `// C++ program to find subarray having``// maximum sum less than or equal to sum``#include ``using` `namespace` `std;` `// To find subarray with maximum sum``// less than or equal to sum``int` `findMaxSubarraySum(``int` `arr[], ``int` `n, ``int` `sum)``{``    ``// To store current sum and``    ``// max sum of subarrays``    ``int` `curr_sum = arr, max_sum = 0, start = 0;` `    ``// To find max_sum less than sum``    ``for` `(``int` `i = 1; i < n; i++) {` `        ``// Update max_sum if it becomes``        ``// greater than curr_sum``        ``if` `(curr_sum <= sum)``           ``max_sum = max(max_sum, curr_sum);` `        ``// If curr_sum becomes greater than``        ``// sum subtract starting elements of array``        ``while` `(curr_sum + arr[i] > sum && start < i) {``            ``curr_sum -= arr[start];``            ``start++;``        ``}``        ` `        ``// Add elements to curr_sum``        ``curr_sum += arr[i];``    ``}` `    ``// Adding an extra check for last subarray``    ``if` `(curr_sum <= sum)``        ``max_sum = max(max_sum, curr_sum);` `    ``return` `max_sum;``}` `// Driver program to test above function``int` `main()``{``    ``int` `arr[] = {6, 8, 9};``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``int` `sum = 20;` `    ``cout << findMaxSubarraySum(arr, n, sum);` `    ``return` `0;``}`

## Java

 `// Java program to find subarray having``// maximum sum less than or equal to sum``public` `class` `Main {` `    ``// To find subarray with maximum sum``    ``// less than or equal to sum``    ``static` `int` `findMaxSubarraySum(``int` `arr[],``                             ``int` `n, ``int` `sum)``    ``{``    ``// To store current sum and``    ``// max sum of subarrays``    ``int` `curr_sum = arr[``0``], max_sum = ``0``, start = ``0``;` `    ``// To find max_sum less than sum``    ``for` `(``int` `i = ``1``; i < n; i++) {` `        ``// Update max_sum if it becomes``        ``// greater than curr_sum``        ``if` `(curr_sum <= sum)``           ``max_sum = Math.max(max_sum, curr_sum);` `        ``// If curr_sum becomes greater than``        ``// sum subtract starting elements of array``        ``while` `(curr_sum + arr[i] > sum && start < i) {``            ``curr_sum -= arr[start];``            ``start++;``        ``}``        ` `        ``// Add elements to curr_sum``        ``curr_sum += arr[i];``    ``}` `    ``// Adding an extra check for last subarray``    ``if` `(curr_sum <= sum)``        ``max_sum = Math.max(max_sum, curr_sum);` `    ``return` `max_sum;``    ``}` `    ``// Driver program to test above function``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `arr[] = { ``1``, ``2``, ``3``, ``4``, ``5` `};``        ``int` `n = arr.length;``        ``int` `sum = ``11``;` `        ``System.out.println(findMaxSubarraySum(arr, n, sum));``    ``}``}`

## Python3

 `# Python3 program to find subarray having``# maximum sum less than or equal to sum` `# To find subarray with maximum sum``# less than or equal to sum``def` `findMaxSubarraySum(arr, n, ``sum``):``    ` `    ``# To store current sum and``    ``# max sum of subarrays``    ``curr_sum ``=` `arr[``0``]``    ``max_sum ``=` `0``    ``start ``=` `0``;` `    ``# To find max_sum less than sum``    ``for` `i ``in` `range``(``1``, n):``        ` `        ``# Update max_sum if it becomes``        ``# greater than curr_sum``        ``if` `(curr_sum <``=` `sum``):``            ``max_sum ``=` `max``(max_sum, curr_sum)` `        ``# If curr_sum becomes greater than sum``        ``# subtract starting elements of array``        ``while` `(curr_sum ``+` `arr[i] > ``sum` `and` `start < i):``            ``curr_sum ``-``=` `arr[start]``            ``start ``+``=` `1``        ` `        ``# Add elements to curr_sum``        ``curr_sum ``+``=` `arr[i]` `    ``# Adding an extra check for last subarray``    ``if` `(curr_sum <``=` `sum``):``        ``max_sum ``=` `max``(max_sum, curr_sum)` `    ``return` `max_sum` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=` `[``6``, ``8``, ``9``]``    ``n ``=` `len``(arr)``    ``sum` `=` `20` `    ``print``(findMaxSubarraySum(arr, n, ``sum``))` `# This code is contributed by``# Surendra_Gangwar`

## C#

 `// C# program to find subarray``// having maximum sum less``//than or equal to sum``using` `System;` `public` `class` `GFG``{` `    ``// To find subarray with maximum``    ``// sum less than or equal``    ``// to sum``    ``static` `int` `findMaxSubarraySum(``int` `[]arr,``                             ``int` `n, ``int` `sum)``    ``{    ``// To store current sum and``    ``// max sum of subarrays``    ``int` `curr_sum = arr, max_sum = 0, start = 0;` `    ``// To find max_sum less than sum``    ``for` `(``int` `i = 1; i < n; i++) {` `        ``// Update max_sum if it becomes``        ``// greater than curr_sum``        ``if` `(curr_sum <= sum)``           ``max_sum = Math.Max(max_sum, curr_sum);` `        ``// If curr_sum becomes greater than``        ``// sum subtract starting elements of array``        ``while` `(curr_sum + arr[i] > sum && start < i) {``            ``curr_sum -= arr[start];``            ``start++;``        ``}``        ` `        ``// Add elements to curr_sum``        ``curr_sum += arr[i];``    ``}` `    ``// Adding an extra check for last subarray``    ``if` `(curr_sum <= sum)``        ``max_sum = Math.Max(max_sum, curr_sum);` `    ``return` `max_sum;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``int` `[]arr = {1, 2, 3, 4, 5};``        ``int` `n = arr.Length;``        ``int` `sum = 11;` `        ``Console.Write(findMaxSubarraySum(arr, n, sum));``    ``}``}` `// This code is contributed by Nitin Mittal.`

## PHP

 ` ``\$sum` `&&``                             ``\$start` `< ``\$i``)``        ``{``            ``\$curr_sum` `-= ``\$arr``[``\$start``];``            ``\$start``++;``        ``}``        ` `        ``// Add elements to curr_sum``        ``\$curr_sum` `+= ``\$arr``[``\$i``];``    ``}` `    ``// Adding an extra check for last subarray``    ``if` `(``\$curr_sum` `<= ``\$sum``)``        ``\$max_sum` `= max(``\$max_sum``, ``\$curr_sum``);` `    ``return` `\$max_sum``;``}` `// Driver Code``\$arr` `= ``array``(6, 8, 9);``\$n` `= sizeof(``\$arr``);``\$sum` `= 20;` `echo` `findMaxSubarraySum(``\$arr``, ``\$n``, ``\$sum``);` `// This code is contributed by ita_c``?>`

## Javascript

 ``
Output:
`17`

If an array with all types(positive, negative or zero) of elements is given, we can use prefix sum and sets and worst case time complexity for that will be O(n.log(n)). You can refer Maximum Subarray sum less than or equal to k using set article for more clarity of this method.

This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.