diff --git a/0122-best-time-to-buy-and-sell-stock-II/memo.md b/0122-best-time-to-buy-and-sell-stock-II/memo.md new file mode 100644 index 0000000..0596300 --- /dev/null +++ b/0122-best-time-to-buy-and-sell-stock-II/memo.md @@ -0,0 +1,12 @@ +### step1 + +わからなかったのでChatGPTに解いてもらった。株を持っている状態と持っていない状態の最大値を更新していくDP。 + +### step2 + +greedyでも解けるということでChatGPTに解いてもらった。最初考えていたが実装できなかったアイデアに近かった。 +https://github.com/naoto-iwase/leetcode/pull/43/changes こちらのコードの実装1も読んでみたが、step2のコードとやってることはほぼ同じだった。 + +### step3 + +step1を3回通すまで書き直し。 diff --git a/0122-best-time-to-buy-and-sell-stock-II/step1.cpp b/0122-best-time-to-buy-and-sell-stock-II/step1.cpp new file mode 100644 index 0000000..41f8e90 --- /dev/null +++ b/0122-best-time-to-buy-and-sell-stock-II/step1.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int maxProfit(vector& 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; + } +}; diff --git a/0122-best-time-to-buy-and-sell-stock-II/step2.cpp b/0122-best-time-to-buy-and-sell-stock-II/step2.cpp new file mode 100644 index 0000000..83d0d17 --- /dev/null +++ b/0122-best-time-to-buy-and-sell-stock-II/step2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int maxProfit(vector& 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; + } +}; diff --git a/0122-best-time-to-buy-and-sell-stock-II/step3.cpp b/0122-best-time-to-buy-and-sell-stock-II/step3.cpp new file mode 100644 index 0000000..41f8e90 --- /dev/null +++ b/0122-best-time-to-buy-and-sell-stock-II/step3.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int maxProfit(vector& 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; + } +};