您的位置:首页 > 其它

[LeetCode]Maximum Product Subarray

2016-11-27 23:07 393 查看
https://leetcode.com/problems/maximum-product-subarray/

第一反应是二维dp,太简单了明显TLE,下面时间O(n),空间O(1)。

以当前位置结尾的乘积最大值,只有可能是三种情况:1、当前位置本身的值nums[i];2、包含当前位置前一位的最小乘积 * 当前位置的值;3、包含当前位置前一位的最大乘积 * 当前位置的值。然后再将当前已经得到的最大值与以当前位置结尾的乘积最大值相比较。

public class Solution {
public int maxProduct(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int maxHere = nums[0], minHere = nums[0], res = nums[0], tempMax, tempMin;
for (int i = 1; i < nums.length; i++) {
tempMax = Math.max(Math.max(maxHere * nums[i], minHere * nums[i]), nums[i]);
tempMin = Math.min(Math.min(maxHere * nums[i], minHere * nums[i]), nums[i]);
res = Math.max(tempMax, res);
maxHere = tempMax;
minHere = tempMin;
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: