Advertisement
aero2146

Maximum Subarray

Dec 29th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.54 KB | None | 0 0
  1. /*
  2. Explanation:
  3. Have a local and global max varaibles. Local max tracks the max between current contiguous numbers and next number. Global max tracks the the max between last highest contiguous number sum and the local max.
  4. */
  5.  
  6. class Solution {
  7.     public int maxSubArray(int[] nums) {
  8.         int maxL, maxG;
  9.         maxL = maxG = nums[0];
  10.        
  11.         for (int i = 1; i < nums.length; i++ ) {
  12.             maxL = Math.max(maxL+nums[i], nums[i]);
  13.             maxG = Math.max(maxG, maxL);
  14.         }
  15.        
  16.         return maxG;
  17.     }
  18. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement