Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

买卖股票的最佳时机

来源Leetcode第121题买卖股票的最佳时机

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。


动态规划

和之前做的最长连续子序和一样,首先先将价格转化为对比前一天的利润,即 dp[i] = dp[i] - dp[i-1],接着就转化为求连续最长子序和这个问题了。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public int maxProfit(int[] prices) {
if(prices.length == 0 )
return 0;
int []dp = new int[prices.length];
for(int i = 1 ; i < prices.length; i++)
dp[i] = prices[i] - prices[i - 1];

int thisSum = 0;
int maxSum = 0;
for(int i = 0; i < prices.length; i++){
thisSum += dp[i];
if(thisSum < 0)
thisSum = 0;
else if(thisSum > maxSum)
maxSum = thisSum;
}

return maxSum;
}

一次遍历

来自题解

对比我自己写的,我想复杂了。
求最大利润的话,只用求最大价格与最小价格之间的差即可,那么可以通过一次遍历求出数组里的最大利润。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
public int maxProfit(int prices[]) {
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minprice)
minprice = prices[i];
else if (prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
return maxprofit;
}