[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;
}
}
第一反应是二维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;
}
}
相关文章推荐
- leetcode做题总结,动态规划II(Maximum Subarray, Maximum Product Subarray)
- 【Leetcode】Maximum Product Subarray (DP)
- 【leetcode】Array—— Maximum Product Subarray(152)
- LeetCode[Dynamic Programming]: Maximum Product Subarray
- leetcode Maximum Product Subarray
- leetcode-Maximum Product Subarray-ZZ
- 【LeetCode】Maximum Product Subarray
- Leetcode: Maximum Product Subarray
- leetcode Maximum Product Subarray
- Leetcode之Maximum Product Subarray 问题
- Leetcode152——Maximum Product Subarray
- 求连续最大子序列积 - leetcode. 152 Maximum Product Subarray
- Leetcode: Maximum Product Subarray
- LeetCode-Maximum Product Subarray
- LeetCode:Maximum Product Subarray
- [leetcode] Maximum Product Subarray
- [leetcode]Maximum Product Subarray
- [Leetcode] Maximum Product Subarray
- LeetCode Maximum Product Subarray
- leetcode Maximum Product Subarray