mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 07:54:07 +00:00
day 44: 121-best-time-to-buy-and-sell-stock
This commit is contained in:
parent
061ad70e40
commit
6df68a24f2
10
121-best-time-to-buy-and-sell-stock/driver.cpp
Normal file
10
121-best-time-to-buy-and-sell-stock/driver.cpp
Normal 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;
|
||||
}
|
||||
24
121-best-time-to-buy-and-sell-stock/soln.cpp
Normal file
24
121-best-time-to-buy-and-sell-stock/soln.cpp
Normal 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;
|
||||
}
|
||||
8
121-best-time-to-buy-and-sell-stock/soln.hpp
Normal file
8
121-best-time-to-buy-and-sell-stock/soln.hpp
Normal 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);
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user