Longest Subarray having sum of elements atmost ‘k’

25 May, 2022
Given an array of integers, our goal 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
Method 1 (Brute Force) Find all the subarrays whose sum is less than or equal to k and return the one with the largest length. Time Complexity : O(n^2) Method 2 (Efficient): An efficient approach is to use the sliding window technique.  
Traverse the array and check if on adding the current element its sum is less than or equal to k.If it’s less than k then add it to the sum and increase the count.Keep track of Maximum count.
Traverse the array and check if on adding the current element its sum is less than or equal to k.
If it’s less than k then add it to the sum and increase the count.
Keep track of Maximum count.
C++
Java
Python3
C#
PHP
Javascript
// A C++ program to find longest subarray with// sum of elements at-least k.#include <bits/stdc++.h>using namespace std; // function to find the length of largest subarray// having sum atmost k.int atMostSum(int arr[], int n, int k){    int sum = 0;    int cnt = 0, maxcnt = 0;     for (int i = 0; i < n; i++) {                 // If adding current element doesn't        // cross limit add it to current window        if ((sum + arr[i]) <= k) {            sum += arr[i];            cnt++;        }         // Else, remove first element of current        // window and add the current element        else if(sum!=0)        {            sum = sum - arr[i - cnt] + arr[i];        }         // keep track of max length.        maxcnt = max(cnt, maxcnt);    }    return maxcnt;} // Driver functionint main(){    int arr[] = {1, 2, 1, 0, 1, 1, 0};    int n = sizeof(arr) / sizeof(arr[0]);    int k = 4;     cout << atMostSum(arr, n, k);    return 0;}
// Java program to find longest subarray with// sum of elements at-least k.import java.util.*; class GFG {         // function to find the length of largest    // subarray having sum atmost k.    public static int atMostSum(int arr[], int n,                                        int k)    {        int sum = 0;        int cnt = 0, maxcnt = 0;             for (int i = 0; i < n; i++) {                         // If adding current element doesn't            // cross limit add it to current window            if ((sum + arr[i]) <= k) {                sum += arr[i];                cnt++;            }                 // Else, remove first element of current            // window.            else if(sum!=0)           {            sum = sum - arr[i - cnt] + arr[i];           }                 // keep track of max length.            maxcnt = Math.max(cnt, maxcnt);        }        return maxcnt;    }         /* Driver program to test above function */    public static void main(String[] args)    {        int arr[] = { 1, 2, 1, 0, 1, 1, 0 };        int n = arr.length;        int k = 4;             System.out.print(atMostSum(arr, n, k));                 }}// This code is contributed by Arnav Kr. Mandal.
# Python3 program to find longest subarray# with sum of elements at-least k. # function to find the length of largest# subarray having sum atmost k.def atMostSum(arr, n, k):    _sum = 0    cnt = 0    maxcnt = 0         for i in range(n):         # If adding current element doesn't        # Cross limit add it to current window        if ((_sum + arr[i]) <= k):            _sum += arr[i]            cnt += 1                 # Else, remove first element of current        # window and add the current element        else if(sum != 0):            _sum = _sum - arr[i - cnt] + arr[i]                 # keep track of max length.        maxcnt = max(cnt, maxcnt)     return maxcnt     # Driver functionarr = [1, 2, 1, 0, 1, 1, 0]n = len(arr)k = 4print(atMostSum(arr, n, k)) # This code is contributed by "Abhishek Sharma 44"
// C# program to find longest subarray// with sum of elements at-least k.using System; class GFG {         // function to find the length of largest    // subarray having sum atmost k.    public static int atMostSum(int []arr, int n,                                           int k)    {        int sum = 0;        int cnt = 0, maxcnt = 0;             for (int i = 0; i < n; i++) {                         // If adding current element doesn't            // cross limit add it to current window            if ((sum + arr[i]) <= k) {                sum += arr[i];                cnt++;            }                 // Else, remove first element            // of current window.            else if(sum!=0)            {                sum = sum - arr[i - cnt] + arr[i];            }                 // keep track of max length.            maxcnt = Math.Max(cnt, maxcnt);        }        return maxcnt;    }         // Driver Code    public static void Main()    {        int []arr = {1, 2, 1, 0, 1, 1, 0};        int n = arr.Length;        int k = 4;             Console.Write(atMostSum(arr, n, k));                 }} // This code is contributed by Nitin Mittal
<?php// A PHP program to find longest// subarray with sum of elements// at-least k. // function to find the length// of largest subarray having// sum atmost k.function atMostSum(&$arr, $n, $k){    $sum = 0;    $cnt = 0;    $maxcnt = 0;     for($i = 0; $i < $n; $i++)    {        // If adding current element        // doesn't cross limit add        // it to current window        if (($sum + $arr[$i]) <= $k)        {            $sum += $arr[$i] ;            $cnt += 1 ;        }         // Else, remove first element        // of current window and add        // the current element        else if($sum != 0)            $sum = $sum - $arr[$i - $cnt] +                               $arr[$i];                 // keep track of max length.        $maxcnt = max($cnt, $maxcnt);    }    return $maxcnt;} // Driver Code$arr = array(1, 2, 1, 0, 1, 1, 0);$n = sizeof($arr);$k = 4; print(atMostSum($arr, $n, $k)); // This code is contributed// by ChitraNayal?>
<script>// A Javascript program to find longest subarray with// sum of elements at-least k. // function to find the length of largest subarray// having sum atmost k.function atMostSum(arr, n, k){    let sum = 0;    let cnt = 0, maxcnt = 0;     for (let i = 0; i < n; i++) {                 // If adding current element doesn't        // cross limit add it to current window        if ((sum + arr[i]) <= k) {            sum += arr[i];            cnt++;        }         // Else, remove first element of current        // window and add the current element        else if(sum!=0)        {            sum = sum - arr[i - cnt] + arr[i];        }         // keep track of max length.        maxcnt = Math.max(cnt, maxcnt);    }    return maxcnt;} // Driver function    let arr = [1, 2, 1, 0, 1, 1, 0];    let n = arr.length;    let k = 4;     document.write(atMostSum(arr, n, k)); </script>
Output:  
5
Time Complexity : O(n), where n represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
This article is contributed by Kshitiz gupta. 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.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
ukasp
souravmahato348
simmytarika5
tamanna17122007
sliding-window
subarray
subarray-sum
Arrays
sliding-window
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures
Python | Using 2D arrays/lists the right way
Find Second largest element in an array
Search an element in a sorted and rotated array
Find the Missing Number