703423. Maximum sum of subarray less than or equal to x

Easy

Maximum sum of subarray less than or equal to x

Summary

Given an array of integers, find the maximum sum of a subarray that is less than or equal to a given integer x. This problem involves using a sliding window approach and two-pointer technique.

Detailed Explanation

To solve this problem, we can use a sliding window approach with two pointers. Initialize two pointers, left and right, to the start of the array. Calculate the sum of the elements between left and right. If the sum is greater than x, move the left pointer to the right until the sum is less than or equal to x. Update the maximum sum if the current sum is greater.

Here's a step-by-step breakdown:

  1. Initialize max_sum to 0, which will store the maximum sum of a subarray that is less than or equal to x.
  2. Initialize left and right pointers to the start of the array.
  3. Calculate the sum of elements between left and right. Let's call this sum current_sum.
  4. If current_sum is greater than x, move the left pointer to the right until current_sum is less than or equal to x.
  5. Update max_sum if current_sum is greater.
  6. Move the right pointer to the right and repeat steps 3-5 until right reaches the end of the array.
  7. Return max_sum.

Time complexity: O(n), where n is the length of the input array. Space complexity: O(1), as we only use a few extra variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxSum(int[] arr, int x) {
    int max_sum = 0;
    int left = 0;
    int right = 0;
    int current_sum = 0;

    while (right < arr.length) {
        current_sum += arr[right];

        while (current_sum > x && left <= right) {
            current_sum -= arr[left];
            left++;
        }

        max_sum = Math.max(max_sum, current_sum);

        right++;
    }

    return max_sum;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.