From feb762806102681ae69d257c1c9a6be4f105751f Mon Sep 17 00:00:00 2001 From: rossy0213 Date: Sun, 26 May 2024 00:38:18 +0900 Subject: [PATCH] add: Best Time to Buy and Sell Stock --- BestTimetoBuyandSellStock/step1.md | 26 +++++++++++ BestTimetoBuyandSellStock/step2.md | 21 +++++++++ BestTimetoBuyandSellStock/step3.md | 71 ++++++++++++++++++++++++++++++ 3 files changed, 118 insertions(+) create mode 100644 BestTimetoBuyandSellStock/step1.md create mode 100644 BestTimetoBuyandSellStock/step2.md create mode 100644 BestTimetoBuyandSellStock/step3.md diff --git a/BestTimetoBuyandSellStock/step1.md b/BestTimetoBuyandSellStock/step1.md new file mode 100644 index 0000000..08aaf29 --- /dev/null +++ b/BestTimetoBuyandSellStock/step1.md @@ -0,0 +1,26 @@ +```go +// For each day, +// We need to check if it's day that we can buy the stock with lower price +// And then check what if we sell it with the lowest price that we found in the past +// Time complexity: O(N) N: number of prices +// Space complexity: 1 +// Time spend: 04:32 +func maxProfit(prices []int) int { + buy := -prices[0]; + sell := buy + prices[0]; + + for _, p := range prices { + buy = max(buy, -p) + sell = max(sell, buy + p) + } + + return sell +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` \ No newline at end of file diff --git a/BestTimetoBuyandSellStock/step2.md b/BestTimetoBuyandSellStock/step2.md new file mode 100644 index 0000000..0b1ce40 --- /dev/null +++ b/BestTimetoBuyandSellStock/step2.md @@ -0,0 +1,21 @@ +```go +// Time spend: 01:10 +func maxProfit(prices []int) int { + buy := -prices[0] + sell := buy + prices[0] + + for _, p := range prices { + buy = max(buy, -p) + sell = max(sell, buy + p) + } + + return sell +} + +func max(a, b int) int { + if a < b { + return b + } + return a +} +``` \ No newline at end of file diff --git a/BestTimetoBuyandSellStock/step3.md b/BestTimetoBuyandSellStock/step3.md new file mode 100644 index 0000000..511b7f5 --- /dev/null +++ b/BestTimetoBuyandSellStock/step3.md @@ -0,0 +1,71 @@ +```go +// Time spend: 01:00 +package main +func maxProfit(prices []int) int { + buy := -prices[0] + sell := buy + -prices[0] + + for _, p := range prices { + buy = max(buy, -p) + sell = max(sell, buy + p) + } + + return sell +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +``` + +```go +// Time spend: 01:02 +package main +func maxProfit(prices []int) int { + buy := -prices[0] + sell := buy + -prices[0] + + for _, p := range prices { + buy = max(buy, -p) + sell = max(sell, buy + p) + } + + return sell +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +``` + +```go +// Time spend: 00:55 +package main +func maxProfit(prices []int) int { + buy := -prices[0] + sell := buy + -prices[0] + + for _, p := range prices { + buy = max(buy, -p) + sell = max(sell, buy + p) + } + + return sell +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +``` \ No newline at end of file