单次版最大股票利益
单次购买的话,遍历数组一次,在过程中记录两个值,一个是最小价格,一个是最大差价(前后),这样复杂度0(n)。
(这个题不适合排序,一是因为排序的话复杂度是nlogn太大了,二是必须前小后大才能赚钱)
单次购买还有另一个理解思路:按照股票差价构成新数组 prices[1]-prices[0], prices[2]-prices[1], prices[3]-prices[2], ..., prices[n-1]-prices[n-2]。求新数组的最大子段和就是我们求得最大利润,假设最大子段和是从新数组第 i 到第 j 项,那么子段和= prices[j]-prices[j-1]+prices[j-1]-prices[j-2]+...+prices[i]-prices[i-1] = prices[j]-prices[i-1], 即prices[j]是最大价格,prices[i-1]是最小价格,且他们满足前后顺序关系。
class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0)
return 0;
int min = prices[0];//min初始赋值为第一位数
int max = 0; //max初始为0
for(int i=1; i < prices.length; i++){
if(min > prices[i])
min = prices[i];
else
max = Math.max(max, prices[i] - min);
}
return max;
}
}
多次版最大股票利益
多次购买的话,对于 [a, b, c, d],如果有 a <= b <= c <= d ,那么最大收益为 d - a。而 d - a = (d - c) + (c - b) + (b - a) ,因此当访问到一个 prices[i] 且 prices[i] - prices[i-1] > 0,那么就把 prices[i] - prices[i-1] 添加到收益中,从而在局部最优的情况下也保证全局最优。同单次购买一样,首先构建股票差价数组,再把数组中所有差价为正的值加起来就是最大利润了。
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for(int i=1; i<prices.length; i++){
if(prices[i] > prices[i-1]) //差值为正数则累加
profit += prices[i] - prices[i-1];
}
return profit;
}
}