
題目出處:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
給一個趨勢,求利潤。
可以從Example 1, 2, 3 得知 若隔天價格下跌就在今日賣出。
若手邊沒庫存 明日價格又較便宜就不買。若手邊有庫存 明日價格攀升即使有利潤 還是保留不賣。
條件相當多,但是主要還是還是看昨天跟今天或者明天跟今天兩天。
也就是說可以設定兩根指針同時往前走。用這方式來解。
#C 代碼:
int maxProfit(int* prices, int pricesSize){
//靜態語言嘛。要先宣告一波。很麻煩。
//分別是買入價格,總利潤,當日利潤以及庫存
int buyPrice=0 , profit=0, dayProfit=0;
bool stock=false;
//如果只有一天 就不用算了吧
if (pricesSize <= 1){
return 0;
}
//判斷第一天要不要買入
if (prices[0] < prices[1]){
buyPrice = prices[0];
stock = true;
}
//開始遍歷每天去趨勢,兩個指針指向昨天跟今天
for(int i=1; i<pricesSize; i++){
if(stock==false && prices[i-1] < prices[i]){
buyPrice = prices[i-1];
stock = true;
}
//看今天趨勢。有利潤就賣
if(stock==true && prices[i-1] > prices[i]){
dayProfit = prices[i-1] - buyPrice;
profit += dayProfit;
stock = false;
}
//如果是最後一天,要執行清倉
if(i==pricesSize-1 && stock==true){
dayProfit = prices[i] - buyPrice;
profit += dayProfit;
stock = false;
}
}
//回傳 總利潤
return profit;
}
#golang 代碼:
func maxProfit(prices []int) int {
var profit, buyPrice int
var stock bool
length := len(prices)
if length == 1 {
return 0
}
if prices[0] < prices[1] {
buyPrice = prices[0]
stock = true
}
for i := 1; i < length; i++ {
if stock == false && prices[i-1] < prices[i] {
buyPrice = prices[i-1]
stock = true
}
if stock == true && prices[i-1] > prices[i] {
profit += prices[i-1] - buyPrice
stock = false
}
if i == length-1 && stock == true {
profit += prices[i] - buyPrice
stock = false
}
}
return profit
}
#Python3 代碼:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
status = False
days = len(prices)
for i in range(days-1):
if prices[i]<prices[i+1]:
if status == False:
buy = prices[i]
status = True
else:
if status:
profit += prices[i]- buy
status = False
if i == (days-2) and status:
profit += prices[i+1] - buy
return profit
return profit
#Java 給想練的人自己寫,我不寫Java的。
以上。如有問題歡迎提出討論。