day 44: 121-best-time-to-buy-and-sell-stock

This commit is contained in:
Kaushik Narayan R 2023-12-03 08:36:44 -07:00
parent 061ad70e40
commit 6df68a24f2
3 changed files with 42 additions and 0 deletions

View File

@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
vector<int> prices{7, 1, 5, 3, 6, 4};
int answer = 5;
Solution soln;
cout << "Found max profit correctly? " << soln.test(prices, answer) << endl;
return 0;
}

View File

@ -0,0 +1,24 @@
#include "soln.hpp"
int Solution::maxProfit(vector<int> &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<int> &prices, int answer)
{
return maxProfit(prices) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxProfit(vector<int> &prices);
bool test(vector<int> &prices, int answer);
};