Advertisement
rajeshinternshala

Untitled

Aug 12th, 2023
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.73 KB | None | 0 0
  1.    public static int atMostSum(List<Integer> a,
  2.                                 int k)
  3.     {
  4.         int sum = 0;
  5.         int cnt = 0, maxcnt = 0;
  6.  
  7.         for (int i = 0; i < a.size(); i++) {
  8.  
  9.             // If adding current element doesn't
  10.             // cross limit add it to current window
  11.             if ((sum + a.get(i)) <= k) {
  12.                 sum += a.get(i);
  13.                 cnt++;
  14.             }
  15.  
  16.             // Else, remove first element of current
  17.             // window.
  18.             else if(sum!=0)
  19.             {
  20.                 sum = sum - a.get(i - cnt) + a.get(i);
  21.             }
  22.  
  23.             // keep track of max length.
  24.             maxcnt = Math.max(cnt, maxcnt);
  25.         }
  26.         return maxcnt;
  27.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement