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