Advertisement
aero2146

Maximum Product Subarray

Dec 29th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.76 KB | None | 0 0
  1. /*
  2. Explanation:
  3. Need to track both max and min as two large negative numbers would make a large positive number. So track curr_min, curr_max, prev_min, prev_max.
  4. */
  5.  
  6. class Solution {
  7.     public int maxProduct(int[] nums) {
  8.         int curr_max, curr_min, prev_max, prev_min, res;
  9.         curr_max = curr_min = prev_max = prev_min = res = nums[0];
  10.        
  11.         for (int i = 1; i < nums.length; i++) {
  12.             curr_max = Math.max(Math.max(nums[i], prev_max*nums[i]), prev_min*nums[i]);
  13.             curr_min = Math.min(Math.min(nums[i], prev_max*nums[i]), prev_min*nums[i]);
  14.            
  15.             res = Math.max(curr_max, res);
  16.            
  17.             prev_max = curr_max;
  18.             prev_min = curr_min;
  19.         }
  20.        
  21.         return res;
  22.     }
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement