Open In App

Max Length of Subarray with Given Sum Limit in JavaScript Array

Last Updated : 06 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array, our task is to find the maximum length of a subarray whose sum does not exceed a given value. We can use different approaches like the Brute Force Approach and the Sliding Window Approach to find the maximum length of a subarray.

Below are the approaches to find the maximum length of a subarray with a sum not exceeding a given value:

Using the Brute Force Approach

In this approach, the code employs a brute force method to find the maximum length of a subarray in JavaScript. It iterates through each possible subarray, calculating the sum and updating the maximum length if the sum does not exceed a given value k. Finally, the method returns the maximum length of the subarray with a sum not exceeding k.

Example: The example uses the Brute Force method to find the maximum length with the sum not exceeding a given value.

JavaScript
function maxSubarrayLengthBruteForce(arr, k) {
    let maxLength = 0;

    for (let start = 0; start < arr.length; start++) {
        let sum = 0;
        for (let end = start; end < arr.length; end++) {
            sum += arr[end];
            if (sum <= k) {
                maxLength = Math.max(maxLength, end - start + 1);
            }
        }
    }

    return maxLength;
}

const array1 = [1, 2, 3, 4, 5];
const k1 = 11;
console.log(maxSubarrayLengthBruteForce(array1, k1));
const array2 = [3, 1, 2, 1];
const k2 = 4;
console.log(maxSubarrayLengthBruteForce(array2, k2));

Output
4
3

Time Complexity: O(n^2)

Space Complexity: O(1)

Using the Sliding Window Approach

In this approach, the sliding window technique is used to find the maximum subarray length whose sum doesn’t exceed a given value k. It iterates through the array, adjusting the window boundaries to maintain the sum within k. Finally, it returns the maximum subarray length found.

Example: The example uses a sliding window technique to find the maximum subarray length with a sum not exceeding a given value.

JavaScript
function maxSubarrayLengthSlidingWindow(arr, k) {
    let maxLength = 0;
    let sum = 0;
    let start = 0;

    for (let end = 0; end < arr.length; end++) {
        sum += arr[end];
        while (sum > k) {
            sum -= arr[start];
            start++;
        }

        maxLength = Math.max(maxLength, end - start + 1);
    }

    return maxLength;
}
const array3 = [1, 2, 3, 4, 5];
const k3 = 11;
console.log(maxSubarrayLengthSlidingWindow(array3, k3));
const array4 = [3, 1, 2, 1];
const k4 = 4;
console.log(maxSubarrayLengthSlidingWindow(array4, k4));

Output
4
3

Time Complexity: O(n)

Space Complexity: O(1)



Previous Article
Next Article

Similar Reads

How to limit a number between a min/max value in JavaScript ?
Given the HTML document. The task is to verify whether the input number is in the specified range or not while taking input a number from the user via the input element. If it is not then make it to lie within the range. These are the two approaches: Table of Content Using the if-else conditionUsing the Math.min() and Math.max() methodsUsing the if
3 min read
CSS Media Queries - max-width or max-height
CSS media queries can help you apply various styles depending on the user's device or viewport properties. You may make responsive designs with them, which change to accommodate various screen sizes, orientations, and device capabilities. The @media rule in CSS is used to write media queries, which can target a wide range of characteristics, includ
3 min read
Set the limit of text length to N lines using CSS
It is possible to limit the text length to [Tex]N[/Tex] lines using CSS. This is known as line clamping or multiple line truncating. There can be two possible cases: Truncating text after 1 line: If you need to truncate text after 1 line then the text-overflow property of CSS can be used. It creates ellipses and gracefully cut off words. div{ white
4 min read
How to limit string length in PHP ?
A string is a sequence of characters in PHP. The length of the string can be limited in PHP using various in-built functions, wherein the string character count can be restricted. Approach 1 (Using for loop): The str_split() function can be used to convert the specified string into the array object. The array elements are individual characters stor
3 min read
How to limit the length of a string in AngularJS ?
Validation of fields is an important process while developing a dynamic web application. In various aspects of security, the validation is quite important. Along with this, the restriction of the limit to the length of a string is also an important process that helps to include the constraint for the maximum length for an input field or a text area
5 min read
Length of the Longest Subarray with Zero Sum using JavaScript
JavaScript allows us to find the longest subarray with zero-sum. We have to return the length of the longest subarray whose sum is equal to zero. There are several approaches in JavaScript to achieve this which are as follows: Table of Content Using Nested loop (Brute force Approach)Using map object in JavaScriptDynamic Programming ApproachUsing Ne
3 min read
How to Find Max Sum (i*arr[i]) with Array Rotations in JavaScript?
Given an array where rotation operations are allowed, the task is to rotate the array any number of times and find the maximum possible sum of i*arr[i]. Examples : Input: arr = [1, 20, 2, 10] Output: 72 Explanation: We can get 72 by rotating array twice. [2, 10, 1, 20] 20*3 + 1*2 + 10*1 + 2*0 = 72 Input: arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9] Output
4 min read
Longest Subarray with Sum Divisible by Given Number in Array with JavaScript
Given an array of integers, the task is to find the longest subarray whose sum is divisible by a given number. Example: Input: [4, 5, 0, -2, -3, 1], k = 5Output: Length = 6Below are the approaches to find the longest subarray with sum divisible by a given number using JavaScript: Table of Content Brute Force ApproachPrefix Sum and HashingBrute Forc
3 min read
Create a Character Limit Textarea using HTML CSS and JavaScript
In this article, we will create a Character Limit Textarea using HTML, CSS, and JavaScript. In this application, we will display the text area as an input component to the user and there is a predefined limit set to accept the input. When the limit is been crossed the user will get the alert message and he will not be able to type further in the te
6 min read
Javascript Program for Queries to find maximum sum contiguous subarrays of given length in a rotating array
Given an array arr[] of N integers and Q queries of the form {X, Y} of the following two types: If X = 1, rotate the given array to the left by Y positions.If X = 2, print the maximum sum subarray of length Y in the current state of the array. Examples:  Input: N = 5, arr[] = {1, 2, 3, 4, 5}, Q = 2, Query[][] = {{1, 2}, {2, 3}}Output:Query 1: 3 4 5
5 min read