File tree Expand file tree Collapse file tree 2 files changed +13
-6
lines changed
src/page-7/714. Best Time to Buy and Sell Stock with Transaction Fee Expand file tree Collapse file tree 2 files changed +13
-6
lines changed Original file line number Diff line number Diff line change @@ -104,19 +104,26 @@ export const maxProfit: MaxProfit = (prices, fee) => {
104
104
105
105
使用貪婪 (Greedy)
106
106
107
+ 決策:
108
+
109
+ - 何時賣出:當當前價格與之前的買入價格之差超過交易費時賣出,以鎖定利潤。
110
+ - 何時更新「買入價」:如果找到比目前追踪的 ` prevPrice ` 更低的價格,就更新 ` prevPrice ` ,以便減少成本。
111
+
107
112
``` ts
108
113
export const maxProfit2: MaxProfit = (prices , fee ) => {
109
- let profit = 0 ;
110
- let prevPrice = prices [0 ];
114
+ let profit = 0 ; // 總利潤
115
+ let prevPrice = prices [0 ]; // 追踪有效的「買入價」
111
116
112
- for (let i = 0 ; i < prices .length ; i ++ ) {
117
+ for (let i = 1 ; i < prices .length ; i ++ ) {
118
+ // 如果達到賣出的利潤門檻
113
119
if (prices [i ] > prevPrice + fee ) {
114
120
profit += prices [i ] - prevPrice - fee ;
115
- prevPrice = prices [i ] - fee ;
121
+ prevPrice = prices [i ] - fee ; // 更新「買入價」以便後續交易
116
122
}
117
123
124
+ // 如果當前價格低於「買入價」
118
125
if (prices [i ] < prevPrice ) {
119
- prevPrice = prices [i ];
126
+ prevPrice = prices [i ]; // 更新「買入價」
120
127
}
121
128
}
122
129
Original file line number Diff line number Diff line change @@ -22,7 +22,7 @@ export const maxProfit2: MaxProfit = (prices, fee) => {
22
22
let profit = 0 ;
23
23
let prevPrice = prices [ 0 ] ;
24
24
25
- for ( let i = 0 ; i < prices . length ; i ++ ) {
25
+ for ( let i = 1 ; i < prices . length ; i ++ ) {
26
26
if ( prices [ i ] > prevPrice + fee ) {
27
27
profit += prices [ i ] - prevPrice - fee ;
28
28
prevPrice = prices [ i ] - fee ;
You can’t perform that action at this time.
0 commit comments