买卖股票最大的收益
121. Best Time to Buy and Sell Stock (Easy)
题目描述:只进行一次交易。
只要记录前面的最小价格,将这个最小价格作为买入价格,然后将当前的价格作为售出价格,查看当前收益是不是最大收益。
class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0)
return 0;
int min = prices[0];
int 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;
}
}
买卖股票的最大收益 II
122. Best Time to Buy and Sell Stock II (Easy)
题目描述:一次股票交易包含买入和卖出,多个交易之间不能交叉进行。
对于 [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;
}
}