買賣股票系列
【leetcode】40-best-time-to-buy-and-sell-stock 力扣 121. 買賣股票的最佳時機
【leetcode】41-best-time-to-buy-and-sell-stock-ii 力扣 122. 買賣股票的最佳時機 II
【leetcode】42-best-time-to-buy-and-sell-stock-iii 力扣 123. 買賣股票的最佳時機 III
【leetcode】43-best-time-to-buy-and-sell-stock-iv 力扣 188. 買賣股票的最佳時機 IV
【leetcode】44-best-time-to-buy-and-sell-stock-with-cooldown 力扣 309. 買賣股票的最佳時機包含冷凍期
【leetcode】45-best-time-to-buy-and-sell-stock-with-cooldown 力扣 714. 買賣股票的最佳時機包含手續(xù)費
開源地址
為了便于大家學(xué)習(xí)毙替,所有實現(xiàn)均已開源谦絮。歡迎 fork + star~
121. 買賣股票的最佳時機
給定一個數(shù)組 prices 蹦肴,它的第 i 個元素 prices[i] 表示一支給定股票第 i 天的價格赂乐。
你只能選擇 某一天 買入這只股票惕澎,并選擇在 未來的某一個不同的日子 賣出該股票汁咏。
設(shè)計一個算法來計算你所能獲取的最大利潤哎壳。
返回你可以從這筆交易中獲取的最大利潤扎酷。如果你不能獲取任何利潤咏瑟,返回 0 拂到。
示例 1:
輸入:[7,1,5,3,6,4]
輸出:5
解釋:在第 2 天(股票價格 = 1)的時候買入,在第 5 天(股票價格 = 6)的時候賣出码泞,最大利潤 = 6-1 = 5 兄旬。
注意利潤不能是 7-1 = 6, 因為賣出價格需要大于買入價格;同時余寥,你不能在買入前賣出股票领铐。
示例 2:
輸入:prices = [7,6,4,3,1]
輸出:0
解釋:在這種情況下, 沒有交易完成, 所以最大利潤為 0。
提示:
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^4
V1-暴力解法
/**
* 最簡單的暴力算法
* @param prices 價格
* @return 結(jié)果
*/
public int maxProfit(int[] prices) {
int maxResult = 0;
for(int i = 0; i < prices.length-1; i++) {
for(int j = i+1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
maxResult = Math.max(profit, maxResult);
}
}
return maxResult;
}
這種解法會超時宋舷。
v2-如何優(yōu)化呢绪撵?
核心的一點:最大的利潤,賣出之前則必須是買入的最小值祝蝠、賣出的最大值音诈。
所以只需要做幾件事:
0)最大值,最小值初始化為 prices[0];
1)記錄最大的利潤 maxResult = maxPrice - minPrice;
2)如果遇到了最小值绎狭,則重新初始化 minPrice, maxPrice
代碼實現(xiàn)
public int maxProfit(int[] prices) {
int maxResult = 0;
int minVal = prices[0];
int maxVal = prices[0];
for(int i = 1; i < prices.length; i++) {
int cur = prices[i];
// 值大于當(dāng)前值
if(cur > maxVal) {
maxResult = Math.max(maxResult, cur - minVal);
}
// 重置
if(cur < minVal) {
minVal = cur;
maxVal = cur;
}
}
return maxResult;
}
V2.5-代碼性能優(yōu)化
優(yōu)化思路
上面的分支判斷太多
核心實現(xiàn)
class Solution {
public int maxProfit(int[] prices) {
int maxResult = 0;
int minVal = prices[0];
for(int i = 0; i < prices.length; i++) {
minVal = Math.min(minVal, prices[i]);
maxResult = Math.max(prices[i] - minVal, maxResult);
}
return maxResult;
}
}
效果
1ms 擊敗100.00%
V3-DP 的思路-貫穿整體解法
思路
我們一共完成了一筆完整的交易细溅,分為兩步:
- b1 買入1
- s1 賣出1
賣出+買入構(gòu)成了完整的交易。
每一天我們都可以決定是否買儡嘶,是否賣喇聊?
初始化
b1 買入時,我們初始化為 -prices[0];
s1 賣出時社付,初始化為0承疲;
代碼
public int maxProfit(int[] prices) {
int b1 = -prices[0];
int s1 = 0;
for(int i = 0; i < prices.length; i++) {
// 賣出第一筆 是否賣邻耕? 不賣則為s1, 賣出則為 b1 + prices[i]
s1 = Math.max(s1, b1 + prices[i]);
// 買入第一筆 是否買鸥咖? 如果買,則花費為當(dāng)前金額;
b1 = Math.max(b1, - prices[i]);
}
return s1;
}