Skip to content

Commit 49b570f

Browse files
committed
258th Commit
1 parent 8b02ab8 commit 49b570f

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

src/page-7/714. Best Time to Buy and Sell Stock with Transaction Fee/README.md

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -104,19 +104,26 @@ export const maxProfit: MaxProfit = (prices, fee) => {
104104

105105
使用貪婪 (Greedy)
106106

107+
決策:
108+
109+
- 何時賣出:當當前價格與之前的買入價格之差超過交易費時賣出,以鎖定利潤。
110+
- 何時更新「買入價」:如果找到比目前追踪的 `prevPrice` 更低的價格,就更新 `prevPrice`,以便減少成本。
111+
107112
```ts
108113
export const maxProfit2: MaxProfit = (prices, fee) => {
109-
let profit = 0;
110-
let prevPrice = prices[0];
114+
let profit = 0; // 總利潤
115+
let prevPrice = prices[0]; // 追踪有效的「買入價」
111116

112-
for (let i = 0; i < prices.length; i++) {
117+
for (let i = 1; i < prices.length; i++) {
118+
// 如果達到賣出的利潤門檻
113119
if (prices[i] > prevPrice + fee) {
114120
profit += prices[i] - prevPrice - fee;
115-
prevPrice = prices[i] - fee;
121+
prevPrice = prices[i] - fee; // 更新「買入價」以便後續交易
116122
}
117123

124+
// 如果當前價格低於「買入價」
118125
if (prices[i] < prevPrice) {
119-
prevPrice = prices[i];
126+
prevPrice = prices[i]; // 更新「買入價」
120127
}
121128
}
122129

src/page-7/714. Best Time to Buy and Sell Stock with Transaction Fee/maxProfit.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ export const maxProfit2: MaxProfit = (prices, fee) => {
2222
let profit = 0;
2323
let prevPrice = prices[0];
2424

25-
for (let i = 0; i < prices.length; i++) {
25+
for (let i = 1; i < prices.length; i++) {
2626
if (prices[i] > prevPrice + fee) {
2727
profit += prices[i] - prevPrice - fee;
2828
prevPrice = prices[i] - fee;

0 commit comments

Comments
 (0)