最大子序和:给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。子数组 是数组中的一个连续部分。
思路: 局部最优:当前连续和为负数的时候立刻放弃,从下一个元素重新计算连续和,因为负数加上下一个元素连续和只会越来越小。
全局最优:选取最大连续和
买卖股票的最佳时机II:给定一个数组 prices ,其中 prices[i] 表示股票第 i 天的价格。在每一天,你可能会决定购买和/或出售股票。你在任何时候 最多 只能持有一股股票。你也可以购买它,然后在同一天出售。返回你能获得的最大利润 。
思路:只需要收集每天正利润就可。
public int maxSubArray(int[] nums){
int result = Integer.MIN_VALUE;
int count = 0;
for (int i = 0; i <nums.length; i++){
count += nums[i];
if (count > result) result = count;
if (count <= 0) count = 0;
}
return result;
}
public int maxProfit(int[] prices ){
int result = 0;
for (int i = 1; i < prices .length; i++){
result += (prices [i] - prices [i - 1]) > 0 ? prices [i] - prices [i - 1] : 0;
}
return result;
}