You are given an array with the price of the stock on the ith day.
You need to max the profit by choosing a day to buy and choosing different day to sell the stock
The solution for this problem is straight forward.
We take 2 variables i.e minPrice and maxProfit. minPrice will have the minimum price from day 0 to I, and maxProfit will have maxProfit from day 0 to i.
The calculation will be, from the day 1, calculate the minPrice with below equation:
minPrice = min(minPrice, prices[i]);
For maxProfit use the below equation:
maxProfit = max(maxProfit, prices[i] – minPrice);
Finally return the maxProfit.
/*
* File : best_time_to_buy_sell_stock.cpp
*/
#include<iostream>
#include<vector>
using namespace std;
int get_max_profit(vector<int> &prices)
{
int maxProfit = 0;
int minPrice = INT_MAX;
for(int i = 0; i < prices.size(); i++)
{
minPrice = min(minPrice, prices[i]);
maxProfit = max(maxProfit, prices[i] - minPrice);
}
return maxProfit;
}
int main()
{
vector<int> prices;
prices.push_back(7);
prices.push_back(1);
prices.push_back(5);
prices.push_back(3);
prices.push_back(6);
prices.push_back(4);
cout<<"The maximum profit is " << get_max_profit(prices)<<endl;
return 0;
}