这道题是Maximum Subarray的follow up
应为乘法所以要考虑负负得正
所以同时记录最小值与最大值
max_products[i] = Math.max(Math.max(max_products[i-1] * nums[i],min_products[i-1]*nums[i]), nums[i]);
min_products[i] = Math.min(Math.min(max_products[i-1] * nums[i],min_products[i-1]*nums[i]), nums[i]);
public class Solution {
/**
* @param nums: An array of integers
* @return: An integer
*/
public int maxProduct(int[] nums) {
// write your code here
int len = nums.length;
Integer[] max_products = new Integer[len];
Integer[] min_products = new Integer[len];
max_products[0] = nums[0];
min_products[0] = nums[0];
int max = max_products[0];
for(int i = 1; i < len; i++) {
max_products[i] = Math.max(Math.max(max_products[i-1] * nums[i],min_products[i-1]*nums[i]), nums[i]);
min_products[i] = Math.min(Math.min(max_products[i-1] * nums[i],min_products[i-1]*nums[i]), nums[i]);
max = Math.max(max_products[i], max);
}
return max;
}
}
Subscribe to:
Post Comments (Atom)
4. Ugly Number
1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...
-
1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...
-
Question: Given string A representative a positive integer which has N digits, remove any k digits of the number, the remaining digit...
-
Thinking: binary Tree 和 Stringbuilder 的联合题 对Stringbuilder 和StringTokenizer的使用方法的考验 public String serialize(TreeNode root) { ...
No comments:
Post a Comment