Open In App

Longest subarray having sum of elements atmost K

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N and an integer K, the task is to find the length of the largest subarray having the sum of its elements at most K, where K > 0.

Examples: 

Input: arr[] = {1, 2, 1, 0, 1, 1, 0}, k = 4
Output: 5
Explanation: {1, 2, 1} => sum = 4, length = 3 {1, 2, 1, 0}, {2, 1, 0, 1} => sum = 4, length = 4 {1, 0, 1, 1, 0} =>5 sum = 3, length = 5

Input: 8, 2, 4, 0, 1, 1, 0, K = 9
Output: 6

Naive Approach – O(n^2) Time and O(1) Space

Generate all the subarrays, and keep updating the largest subarray whose sum is less than or equal to K.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the length of largest subarray
// having sum at most k.
int atMostSum(vector<int>& arr, int k) {
    int res = 0;

    for (int i = 0; i < arr.size(); i++) {
      
        // Find current sum (between i and j)
        int curr = 0;
        for (int j = i; j < arr.size(); j++) {
            curr += arr[j];

            if (curr <= k) {
                res = max(res, (j - i + 1));
            } else {
                break;
            }
        }
    }

    return res;
}

int main() {
    vector<int> arr = { 1, 2, 1, 0, 1, 1, 0 };
    int k = 4;
    int res = atMostSum(arr, k);
    cout << res << endl;
    return 0;
}
C
#include <stdio.h>

// Function to find the length of the largest subarray
// having sum at most k.
int atMostSum(int* arr, int n, int k) {
    int res = 0;

    for (int i = 0; i < n; i++) {
      
        // Find current sum (between i and j)
        int curr = 0;
        for (int j = i; j < n; j++) {
            curr += arr[j];

            if (curr <= k) {
                res = (j - i + 1) > res ? (j - i + 1) : res;
            } else {
                break;
            }
        }
    }

    return res;
}

int main() {
    int arr[] = { 1, 2, 1, 0, 1, 1, 0 };
    int k = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
    int res = atMostSum(arr, n, k);
    printf("%d\n", res);
    return 0;
}
Java
import java.util.*;

class GfG {

    // Function to find the length of the largest subarray
    // having sum at most k.
    static int atMostSum(int[] arr, int k) {
        int res = 0;

        // Iterate through the array starting at each element
        for (int i = 0; i < arr.length; i++) {

            // Find current sum (between i and j)
            int curr = 0;
            for (int j = i; j < arr.length; j++) {
                curr += arr[j];

                // If current sum is within the limit, update result
                if (curr <= k) {
                    res = Math.max(res, j - i + 1);
                } 
                // If sum exceeds k, stop further addition for this subarray
                else {
                    break;
                }
            }
        }

        // Return the maximum length of subarray found
        return res;
    }

    public static void main(String[] args) {
        // Define the input array and the maximum sum k
        int[] arr = { 1, 2, 1, 0, 1, 1, 0 };
        int k = 4;

        // Call the function and store the result
        int res = atMostSum(arr, k);

        // Print the result
        System.out.println(res);
    }
}
Python
# Function to find the length of the largest subarray
# having sum at most k.
def atMostSum(arr, k):
    res = 0

    for i in range(len(arr)):
        
        # Find current sum (between i and j)
        curr = 0
        for j in range(i, len(arr)):
            curr += arr[j]

            if curr <= k:
                res = max(res, j - i + 1)
            else:
                break

    return res

# Driver code
arr = [1, 2, 1, 0, 1, 1, 0]
k = 4
res = atMostSum(arr, k)
print(res)
C#
using System;

class GfG {

    // Function to find the length of the largest subarray
    // having sum at most k.
    static int atMostSum(int[] arr, int k) {
        int res = 0;

        for (int i = 0; i < arr.Length; i++) {

            // Find current sum (between i and j)
            int curr = 0;
            for (int j = i; j < arr.Length; j++) {
                curr += arr[j];

                if (curr <= k) {
                    res = Math.Max(res, j - i + 1);
                } else {
                    break;
                }
            }
        }

        return res;
    }

    public static void Main() {
        int[] arr = { 1, 2, 1, 0, 1, 1, 0 };
        int k = 4;
        int res = atMostSum(arr, k);
        Console.WriteLine(res);
    }
}
JavaScript
// Function to find the length of the largest subarray
// having sum at most k.
function atMostSum(arr, k) {
    let res = 0;

    for (let i = 0; i < arr.length; i++) {
        
        // Find current sum (between i and j)
        let curr = 0;
        for (let j = i; j < arr.length; j++) {
            curr += arr[j];

            if (curr <= k) {
                res = Math.max(res, j - i + 1);
            } else {
                break;
            }
        }
    }

    return res;
}

// Driver code
const arr = [1, 2, 1, 0, 1, 1, 0];
const k = 4;
const res = atMostSum(arr, k);
console.log(res);

Output
5

[Expected Approach – Window Sliding – O(n) Time and O(1) Space

We maintain a dynamic sized window of elements having sum less than k.

  1. Keep adding elements while the current sum is less than or equal to k. Keep updating result also if required.
  2. Whenever sum becomes more than k, keep removing elements while the sum is more than k.
  3. IF we find an element greater than k, we reset the window size as 0 and sum as 0.
C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the length of the largest subarray
// having a sum at most k.
int atMostSum(vector<int>& arr, int k) {
  
    // Initialize the current sum to 0.
    int sum = 0;

    // Initialize a counter for the current 
    // subarray (or window) length to 0.
    int cnt = 0;

    // Initialize the result to 0.
    int res = 0;

    for (int i = 0; i < arr.size(); i++) {
        if (arr[i] > k) {
          
            // Reset the counter if an element 
            // is greater than k.
            sum = 0;
            cnt = 0;
            continue;
        }

        if ((sum + arr[i]) <= k) {
          
            // Include the current element in the subarray.
            // Increment the subarray length.
            cnt++;
            sum += arr[i];
        } else {
            cnt++;
            sum += arr[i];

            // If the sum exceeds k, remove elements from
            // the subarray until the sum is less than or
            // equal to k.
            while (sum > k) {
                sum -= arr[i - cnt + 1];
                cnt--;
            }
        }

        // Update the result with the maximum subarray length.
        res = max(cnt, res);
    }
    return res;
}

int main() {
    vector<int> arr = { 1, 2, 1, 0, 1, 1, 0 };
    int k = 4;
    cout << atMostSum(arr, k);
    return 0;
}
C
#include <stdio.h>

// Function to find the length of the largest subarray
// having a sum at most k.
int atMostSum(int* arr, int n, int k) {

    // Initialize the current sum to 0.
    int sum = 0;

    // Initialize a counter for the current 
    // subarray (or window) length to 0.
    int cnt = 0;

    // Initialize the result to 0.
    int res = 0;

    for (int i = 0; i < n; i++) {
        if (arr[i] > k) {

            // Reset the counter if an element 
            // is greater than k.
            sum = 0;
            cnt = 0;
            continue;
        }

        if ((sum + arr[i]) <= k) {

            // Include the current element in the subarray.
            // Increment the subarray length.
            cnt++;
            sum += arr[i];
        } else {
            cnt++;
            sum += arr[i];

            // If the sum exceeds k, remove elements from
            // the subarray until the sum is less than or
            // equal to k.
            while (sum > k) {
                sum -= arr[i - cnt + 1];
                cnt--;
            }
        }

        // Update the result with the maximum subarray length.
        res = cnt > res ? cnt : res;
    }
    return res;
}

int main() {
    int arr[] = { 1, 2, 1, 0, 1, 1, 0 };
    int k = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", atMostSum(arr, n, k));
    return 0;
}
Java
import java.util.*;

class GfG {

    // Function to find the length of the largest subarray
    // having a sum at most k.
    static int atMostSum(int[] arr, int k) {

        // Initialize the current sum to 0.
        int sum = 0;

        // Initialize a counter for the current 
        // subarray (or window) length to 0.
        int cnt = 0;

        // Initialize the result to 0.
        int res = 0;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > k) {

                // Reset the counter if an element 
                // is greater than k.
                sum = 0;
                cnt = 0;
                continue;
            }

            if ((sum + arr[i]) <= k) {

                // Include the current element in the subarray.
                // Increment the subarray length.
                cnt++;
                sum += arr[i];
            } else {
                cnt++;
                sum += arr[i];

                // If the sum exceeds k, remove elements from
                // the subarray until the sum is less than or
                // equal to k.
                while (sum > k) {
                    sum -= arr[i - cnt + 1];
                    cnt--;
                }
            }

            // Update the result with the maximum subarray length.
            res = Math.max(cnt, res);
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = { 1, 2, 1, 0, 1, 1, 0 };
        int k = 4;
        System.out.println(atMostSum(arr, k));
    }
}
Python
# Function to find the length of the largest subarray
# having a sum at most k.
def atMostSum(arr, k):

    # Initialize the current sum to 0.
    sum = 0

    # Initialize a counter for the current 
    # subarray (or window) length to 0.
    cnt = 0

    # Initialize the result to 0.
    res = 0

    for i in range(len(arr)):
        if arr[i] > k:

            # Reset the counter if an element 
            # is greater than k.
            sum = 0
            cnt = 0
            continue

        if sum + arr[i] <= k:

            # Include the current element in the subarray.
            # Increment the subarray length.
            cnt += 1
            sum += arr[i]
        else:
            cnt += 1
            sum += arr[i]

            # If the sum exceeds k, remove elements from
            # the subarray until the sum is less than or
            # equal to k.
            while sum > k:
                sum -= arr[i - cnt + 1]
                cnt -= 1

        # Update the result with the maximum subarray length.
        res = max(cnt, res)
    
    return res

# Driver code
arr = [1, 2, 1, 0, 1, 1, 0]
k = 4
print(atMostSum(arr, k))
C#
using System;

class GfG {

    // Function to find the length of the largest subarray
    // having a sum at most k.
    static int atMostSum(int[] arr, int k) {

        // Initialize the current sum to 0.
        int sum = 0;

        // Initialize a counter for the current 
        // subarray (or window) length to 0.
        int cnt = 0;

        // Initialize the result to 0.
        int res = 0;

        for (int i = 0; i < arr.Length; i++) {
            if (arr[i] > k) {

                // Reset the counter if an element 
                // is greater than k.
                sum = 0;
                cnt = 0;
                continue;
            }

            if (sum + arr[i] <= k) {

                // Include the current element in the subarray.
                // Increment the subarray length.
                cnt++;
                sum += arr[i];
            } else {
                cnt++;
                sum += arr[i];

                // If the sum exceeds k, remove elements from
                // the subarray until the sum is less than or
                // equal to k.
                while (sum > k) {
                    sum -= arr[i - cnt + 1];
                    cnt--;
                }
            }

            // Update the result with the maximum subarray length.
            res = Math.Max(cnt, res);
        }
        return res;
    }

    public static void Main() {
        int[] arr = { 1, 2, 1, 0, 1, 1, 0 };
        int k = 4;
        Console.WriteLine(atMostSum(arr, k));
    }
}
JavaScript
// Function to find the length of the largest subarray
// having a sum at most k.
function atMostSum(arr, k) {

    // Initialize the current sum to 0.
    let sum = 0;

    // Initialize a counter for the current 
    // subarray (or window) length to 0.
    let cnt = 0;

    // Initialize the result to 0.
    let res = 0;

    for (let i = 0; i < arr.length; i++) {
        if (arr[i] > k) {

            // Reset the counter if an element 
            // is greater than k.
            sum = 0;
            cnt = 0;
            continue;
        }

        if (sum + arr[i] <= k) {

            // Include the current element in the subarray.
            // Increment the subarray length.
            cnt++;
            sum += arr[i];
        } else {
            cnt++;
            sum += arr[i];

            // If the sum exceeds k, remove elements from
            // the subarray until the sum is less than or
            // equal to k.
            while (sum > k) {
                sum -= arr[i - cnt + 1];
                cnt--;
            }
        }

        // Update the result with the maximum subarray length.
        res = Math.max(cnt, res);
    }
    return res;
}

// Driver code
const arr = [1, 2, 1, 0, 1, 1, 0];
const k = 4;
console.log(atMostSum(arr, k));

Output
5

Time complexity is O(n) because every element goes into the window atmost once and comes out of the window at most once and both of these operations are O(1)



Next Article
Article Tags :
Practice Tags :

Similar Reads