动态规划 03

75 阅读1分钟

LeetCode 152

原题链接

题解

官方题解

代码如下:

/**
 * 
 * 动态规划
 * 
 * Code by java
 */

class Solution {
	public int maxProduct(int[] nums) {
		int n = nums.length;
		if (n == 0) return 0;
		if (n == 1) return nums[0];
		int res = nums[0];
		int max = nums[0], min = nums[0];
		for (int i = 1; i < n; i++) {
			int tmpMax = max, tmpMin = min;
			max = Math.max(Math.max(tmpMin * nums[i], tmpMax * nums[i]), nums[i]);
			min = Math.min(Math.min(tmpMin * nums[i], tmpMax * nums[i]), nums[i]);
			res = Math.max(res, max);
		}
		return res;
	}

//	public static void main(String[] args) {
//		int[] pp = new int[] { -4, -3, -2 };
//		Solution kk = new Solution();
//		System.out.println(kk.maxProduct(pp));
//	}
}