From ca54a1ccef58fe13cf420dd93653e7178b9a04be Mon Sep 17 00:00:00 2001 From: Stackingrule <38368554+Stackingrule@users.noreply.github.com> Date: Sat, 26 Dec 2020 15:19:58 +0800 Subject: [PATCH] feat:add Solution.cpp for 0121. Best Time to Buy and Sell Stock --- .../Solution.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.cpp diff --git a/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.cpp b/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.cpp new file mode 100644 index 0000000000000..292ff9db68855 --- /dev/null +++ b/solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int maxProfit(vector& prices) { + const int n = prices.size(); + if (n < 1) return 0; + vector min_prices(n); + vector max_profit(n); + min_prices[0] = prices[0]; + max_profit[0] = 0; + for (int i = 1; i < n; ++i) { + min_prices[i] = min(min_prices[i - 1], prices[i]); + max_profit[i] = max(max_profit[i - 1], prices[i] - min_prices[i - 1]); + } + + return max_profit[n - 1]; + } +}; \ No newline at end of file