Given an array arr[] of integers and a number x, find the sum of subarray having a maximum sum less than or equal to the given value of x.
Examples:
Input: arr[] = [1, 2, 3, 4, 5], x = 11
Output: 10
Explanation: Subarray having maximum sum is [1, 2, 3, 4].
Input: arr[] = [2, 4, 6, 8, 10], x = 7
Output: 6
Explanation: Subarray having maximum sum is [2, 4] or [6].
Table of Content
[Naive Approach] Generate All Subarrays - O(n ^ 2) Time and O(1) Space
The idea is to generate every possible subarray, calculate its sum, and keep track of the maximum subarray sum that does not exceed x.
Working of Approach:
- Iterate over every possible starting index.
- For each starting index, extend the subarray one element at a time.
- Compute the running sum of the current subarray.
- If the sum is less than or equal to x, update the answer.
- After checking all subarrays, return the maximum valid sum.
#include <bits/stdc++.h>
using namespace std;
int maxSum(vector<int> &arr, int x)
{
int n = arr.size();
int res = 0;
// Generate all possible subarrays
for (int i = 0; i < n; i++)
{
int sum = 0;
for (int j = i; j < n; j++)
{
sum += arr[j];
// Update answer if sum does not exceed x
if (sum <= x)
res = max(res, sum);
}
}
return res;
}
int main()
{
vector<int> arr = {2, 4, 6, 8, 10};
int x = 7;
cout << maxSum(arr, x);
return 0;
}
import java.util.Arrays;
public class GFG {
public static int maxSum(int[] arr, int x)
{
int n = arr.length;
int res = 0;
// Generate all possible subarrays
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
// Update answer if sum does not exceed x
if (sum <= x)
res = Math.max(res, sum);
}
}
return res;
}
public static void main(String[] args)
{
int[] arr = { 2, 4, 6, 8, 10 };
int x = 7;
System.out.println(maxSum(arr, x));
}
}
def maxSum(arr, x):
n = len(arr)
res = 0
# Generate all possible subarrays
for i in range(n):
sum = 0
for j in range(i, n):
sum += arr[j]
# Update answer if sum does not exceed x
if sum <= x:
res = max(res, sum)
return res
if __name__ == '__main__':
arr = [2, 4, 6, 8, 10]
x = 7
print(maxSum(arr, x))
using System;
class GFG {
static int maxSum(int[] arr, int x)
{
int n = arr.Length;
int res = 0;
// Generate all possible subarrays
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
// Update answer if sum does not exceed x
if (sum <= x)
res = Math.Max(res, sum);
}
}
return res;
}
static void Main()
{
int[] arr = { 2, 4, 6, 8, 10 };
int x = 7;
Console.WriteLine(maxSum(arr, x));
}
}
function maxSum(arr, x)
{
let n = arr.length;
let res = 0;
// Generate all possible subarrays
for (let i = 0; i < n; i++) {
let sum = 0;
for (let j = i; j < n; j++) {
sum += arr[j];
// Update answer if sum does not exceed x
if (sum <= x)
res = Math.max(res, sum);
}
}
return res;
}
// Driver Code
let arr = [ 2, 4, 6, 8, 10 ];
let x = 7;
console.log(maxSum(arr, x));
Output
6
[Expected Approach] Using Sliding Window - O(n) Time and O(1) Space
The idea is to use a sliding window. Since all array elements are positive, expanding the window increases the sum while shrinking it decreases the sum. This property allows us to maintain the maximum valid window in linear time.
Let us understand with an example:
Input: arr[] = [2, 4, 6, 8, 10], x = 7
- Initially, the window contains {2} with curr_sum = 2, max_sum = 0, and start = 0.
- Add 4 to the window. The sum becomes 6, which is within x, so update max_sum = 6.
- Before adding 6, the sum would become 12, so remove 2 and then 4 from the left. Add 6, making the window {6} with curr_sum = 6.
- Similarly, before adding 8 and 10, shrink the window from the left until adding the current element keeps the window sum less than or equal to x.
- The maximum window sum that never exceeds 7 is 6.
#include <bits/stdc++.h>
using namespace std;
// Function to return the maximum subarray sum
// less than or equal to x
int maxSum(vector<int> &arr, int x)
{
int curr_sum = arr[0], max_sum = 0;
int start = 0;
// Traverse the array
for (int i = 1; i < arr.size(); i++)
{
// Update the answer if current sum is valid
if (curr_sum <= x)
max_sum = max(max_sum, curr_sum);
// Shrink the window while adding the current
// element makes the sum exceed x
while (curr_sum + arr[i] > x && start < i)
{
curr_sum -= arr[start];
start++;
}
// Include the current element in the window
curr_sum += arr[i];
}
// Check the last window
if (curr_sum <= x)
max_sum = max(max_sum, curr_sum);
return max_sum;
}
int main()
{
vector<int> arr = {2, 4, 6, 8, 10};
int x = 7;
cout << maxSum(arr, x);
return 0;
}
import java.util.Arrays;
public class GFG {
// Function to return the maximum subarray sum
// less than or equal to x
public static int maxSum(int[] arr, int x)
{
int curr_sum = arr[0], max_sum = 0;
int start = 0;
// Traverse the array
for (int i = 1; i < arr.length; i++) {
// Update the answer if current sum is valid
if (curr_sum <= x)
max_sum = Math.max(max_sum, curr_sum);
// Shrink the window while adding the current
// element makes the sum exceed x
while (curr_sum + arr[i] > x && start < i) {
curr_sum -= arr[start];
start++;
}
// Include the current element in the window
curr_sum += arr[i];
}
// Check the last window
if (curr_sum <= x)
max_sum = Math.max(max_sum, curr_sum);
return max_sum;
}
public static void main(String[] args)
{
int[] arr = { 2, 4, 6, 8, 10 };
int x = 7;
System.out.println(maxSum(arr, x));
}
}
def maxSum(arr, x):
curr_sum = arr[0]
max_sum = 0
start = 0
# Traverse the array
for i in range(1, len(arr)):
# Update the answer if current sum is valid
if curr_sum <= x:
max_sum = max(max_sum, curr_sum)
# Shrink the window while adding the current
# element makes the sum exceed x
while curr_sum + arr[i] > x and start < i:
curr_sum -= arr[start]
start += 1
# Include the current element in the window
curr_sum += arr[i]
# Check the last window
if curr_sum <= x:
max_sum = max(max_sum, curr_sum)
return max_sum
if __name__ == '__main__':
arr = [2, 4, 6, 8, 10]
x = 7
print(maxSum(arr, x))
using System;
public class GFG {
// Function to return the maximum subarray sum
// less than or equal to x
public static int maxSum(int[] arr, int x)
{
int curr_sum = arr[0], max_sum = 0;
int start = 0;
// Traverse the array
for (int i = 1; i < arr.Length; i++) {
// Update the answer if current sum is valid
if (curr_sum <= x)
max_sum = Math.Max(max_sum, curr_sum);
// Shrink the window while adding the current
// element makes the sum exceed x
while (curr_sum + arr[i] > x && start < i) {
curr_sum -= arr[start];
start++;
}
// Include the current element in the window
curr_sum += arr[i];
}
// Check the last window
if (curr_sum <= x)
max_sum = Math.Max(max_sum, curr_sum);
return max_sum;
}
public static void Main()
{
int[] arr = { 2, 4, 6, 8, 10 };
int x = 7;
Console.WriteLine(maxSum(arr, x));
}
}
function maxSum(arr, x)
{
let curr_sum = arr[0], max_sum = 0;
let start = 0;
// Traverse the array
for (let i = 1; i < arr.length; i++) {
// Update the answer if current sum is valid
if (curr_sum <= x)
max_sum = Math.max(max_sum, curr_sum);
// Shrink the window while adding the current
// element makes the sum exceed x
while (curr_sum + arr[i] > x && start < i) {
curr_sum -= arr[start];
start++;
}
// Include the current element in the window
curr_sum += arr[i];
}
// Check the last window
if (curr_sum <= x)
max_sum = Math.max(max_sum, curr_sum);
return max_sum;
}
// Driver Code
const arr = [ 2, 4, 6, 8, 10 ];
const x = 7;
console.log(maxSum(arr, x));
Output
6