Advertisement
Guest User

sliding sum

a guest
Oct 15th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | None | 0 0
  1. public static void main(String[] args) {
  2.         // TODO code application logic here
  3.         Scanner sc = new Scanner(System.in);
  4.         int n = sc.nextInt();
  5.         int sum = sc.nextInt();
  6.         int [] nums = new int[n];
  7.        
  8.         for(int i=0; i<n;i++){
  9.             nums[i] =sc.nextInt();
  10.         }
  11.         sc.close();
  12.         /*
  13.         for(int i=0; i<n;i++){
  14.             System.out.println(nums[i]);
  15.         }
  16.         */
  17.         int currentSum = nums[0];
  18.         int max = 0;
  19.         int i= 0;
  20.         int j = i+1;
  21.         while(i<n-1 && j<n)
  22.         {
  23.             currentSum += nums[j];
  24.             j++;
  25.             if(currentSum > sum)
  26.             {
  27.                 currentSum -= nums[i];
  28.                 i++;
  29.             }
  30.             else{
  31.                max = Math.max(max,currentSum);
  32.             }                        
  33.         }
  34.        
  35.         System.out.println("Max Sum: "+ max);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement