From 6df68a24f28942f332b73c3ebee337286543bcde Mon Sep 17 00:00:00 2001 From: Kaushik Narayan R Date: Sun, 3 Dec 2023 08:36:44 -0700 Subject: [PATCH] day 44: 121-best-time-to-buy-and-sell-stock --- .../driver.cpp | 10 ++++++++ 121-best-time-to-buy-and-sell-stock/soln.cpp | 24 +++++++++++++++++++ 121-best-time-to-buy-and-sell-stock/soln.hpp | 8 +++++++ 3 files changed, 42 insertions(+) create mode 100644 121-best-time-to-buy-and-sell-stock/driver.cpp create mode 100644 121-best-time-to-buy-and-sell-stock/soln.cpp create mode 100644 121-best-time-to-buy-and-sell-stock/soln.hpp diff --git a/121-best-time-to-buy-and-sell-stock/driver.cpp b/121-best-time-to-buy-and-sell-stock/driver.cpp new file mode 100644 index 0000000..a904656 --- /dev/null +++ b/121-best-time-to-buy-and-sell-stock/driver.cpp @@ -0,0 +1,10 @@ +#include "soln.hpp" + +int main() +{ + vector prices{7, 1, 5, 3, 6, 4}; + int answer = 5; + Solution soln; + cout << "Found max profit correctly? " << soln.test(prices, answer) << endl; + return 0; +} \ No newline at end of file diff --git a/121-best-time-to-buy-and-sell-stock/soln.cpp b/121-best-time-to-buy-and-sell-stock/soln.cpp new file mode 100644 index 0000000..418b499 --- /dev/null +++ b/121-best-time-to-buy-and-sell-stock/soln.cpp @@ -0,0 +1,24 @@ +#include "soln.hpp" + +int Solution::maxProfit(vector &prices) +{ + if (prices.size() == 1) + return 0; + int max_profit = 0, buying_day = 0, cur_profit = 0; + for (int i = 0; i < prices.size(); i++) + { + // cheaper buy day + if (prices[i] < prices[buying_day]) + buying_day = i; + cur_profit = prices[i] - prices[buying_day]; + // more profit + if (max_profit < cur_profit) + max_profit = cur_profit; + } + return max_profit; +} + +bool Solution::test(vector &prices, int answer) +{ + return maxProfit(prices) == answer; +} diff --git a/121-best-time-to-buy-and-sell-stock/soln.hpp b/121-best-time-to-buy-and-sell-stock/soln.hpp new file mode 100644 index 0000000..d48af77 --- /dev/null +++ b/121-best-time-to-buy-and-sell-stock/soln.hpp @@ -0,0 +1,8 @@ +#include +using namespace std; +class Solution +{ +public: + int maxProfit(vector &prices); + bool test(vector &prices, int answer); +}; \ No newline at end of file