Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions 0122-best-time-to-buy-and-sell-stock-II/memo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
### step1

わからなかったのでChatGPTに解いてもらった。株を持っている状態と持っていない状態の最大値を更新していくDP。

### step2

greedyでも解けるということでChatGPTに解いてもらった。最初考えていたが実装できなかったアイデアに近かった。
https://github.com/naoto-iwase/leetcode/pull/43/changes こちらのコードの実装1も読んでみたが、step2のコードとやってることはほぼ同じだった。

### step3

step1を3回通すまで書き直し。
17 changes: 17 additions & 0 deletions 0122-best-time-to-buy-and-sell-stock-II/step1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution {
public:
int maxProfit(vector<int>& prices) {
int hold = -prices[0];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

入力配列の長さをチェックすると,LeetCodeの問題が置く制約を満たさないような入力に対しても正常に動く実装になりますね.エラーを返す実装でもいいと思います.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

動詞の原形から始まる変数名は関数名のような印象を受けます. holdingnot_holding などはいかがでしょうか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

了解です!ご指摘ありがとうございます。

int not_hold = 0;

for (int i = 1; i < prices.size(); i++) {
int new_hold = max(hold, not_hold - prices[i]);
int new_not_hold = max(not_hold, hold + prices[i]);

hold = new_hold;
not_hold = new_not_hold;
}

return not_hold;
}
};
12 changes: 12 additions & 0 deletions 0122-best-time-to-buy-and-sell-stock-II/step2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
};
17 changes: 17 additions & 0 deletions 0122-best-time-to-buy-and-sell-stock-II/step3.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution {
public:
int maxProfit(vector<int>& prices) {
int hold = -prices[0];
int not_hold = 0;

for (int i = 1; i < prices.size(); i++) {
int new_hold = max(hold, not_hold - prices[i]);
int new_not_hold = max(not_hold, hold + prices[i]);

hold = new_hold;
not_hold = new_not_hold;
}

return not_hold;
}
};