class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0)
throw new RuntimeException("Invalid input!");
int currSum = 0;
int maxSum = Integer.MIN_VALUE;
for (int num : nums) {
currSum = currSum <= 0 ? num : num + currSum;
maxSum = Math.max(currSum, maxSum);
}
return maxSum;
}
}
2. LeetCode 152
2.1 复杂度分析
二重循环:暴力搜索;无需复习
时间复杂度:O(n2)O(n^2)O(n2);
空间复杂度:O(1)O(1)O(1);
动态规划:
时间复杂度:O(n)O(n)O(n);
空间复杂度:O(1)O(1)O(1);
2.2 动态规划
解题思路:
LeetCode 53:加法;
若前序元素贡献为正值,则累加;
若前序元素贡献为负值,则不累加;
LeetCode 152:乘法;
首先不考虑累乘2个负数,得到更大正数的情况,当前值有2种取值可能;
恰为当前值;
前序元素与当前值的乘积;
其次考虑累乘2个负数,得到更大正数的情况;
创建2个变量 max 和 min;
max=Math.max(num,num∗max)max = Math.max(num, num * max)max=Math.max(num,num∗max);
min=Math.min(num,num∗min)min = Math.min(num, num * min)min=Math.min(num,num∗min);
若当前值为负数,则将 max 和 min 互换后执行后续计算;
class Solution {
public int maxProduct(int[] nums) {
if (nums == null || nums.length == 0)
throw new RuntimeException("Invalid input!");
int max = 1;
int min = 1;
int res = Integer.MIN_VALUE;
for (int num : nums) {
if (num < 0) {
int temp = max;
max = min;
min = temp;
}
max = Math.max(num, num * max);
min = Math.min(num, num * min);
res = Math.max(max, res);
}
return res;
}
}
3. Summary
参见 LeetCode 53 & 152;
DP 问题:用递归的方式思考,用迭代的方式求解;
References
https://leetcode-cn.com/u/hqpan/. ↩︎
https://github.com/hqpan/LeetCode. ↩︎