Untitled

 avatar
unknown
plain_text
a month ago
1.1 kB
1
Indexable
public class MaxSumSubarray {
    public int maxSumSubarrayOfSizeK(int[] nums, int k) {
        int i = 0; // Start of the window
        int j = 0; // End of the window
        int sum = 0;
        int maxSum = 0;
        int leftBoundary = -1;
        int rightBoundary = - 1;

    // intial process of k size window
        for(int j=0;j<k;j++)
        {
          sum += nums[j];
        }  

       // maxsum of initial processed window.         
        maxSum = Math.max(maxSum,sum);
        leftBoundary = 0;
        rightBoundary = k-1; 

     // then slide the window by +1 and dec by -1
        while(j<n)
        {
             sum+=a[j];
             sum-=a[i];
             maxSum = Math.max(maxSum,sum);

             // for boundary 
             /*
                i++;  // instead of placing below  
                if(sum>maxSum)
                  {
                    leftBoundary = i;
                    rightBoundary = j; 
                  }
            
             */ 

             i++;
             j++;
        }
        
        return maxSum;
    }

   
}
Leave a Comment