Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
Solution:DP
思路:
Time Complexity: O(N) Space Complexity: O(1)
Solution Code:
class Solution {
public int maxProduct(int[] nums) {
int g_max = nums[0];
int c_max = nums[0];
int c_min = nums[0];
for(int i = 1; i < nums.length; i++) {
int new_c_max = Math.max(Math.max(nums[i], nums[i] * c_max), nums[i] * c_min);
int new_c_min = Math.min(Math.min(nums[i], nums[i] * c_max), nums[i] * c_min);
g_max = Math.max(g_max, new_c_max);
c_max = new_c_max;
c_min = new_c_min;
}
return g_max;
}
}