Best time to buy and sell the stock
You are given an array prices
where prices[i]
is the price of a given stock on the i<sup>th</sup>
day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
.
Solution:
In this problem, we are given an array prices and we need to buy the stock at some point of time and we need to sell that stock at another time , and the answer will be the difference between the selling price and buying prize.
so to solve this problem, we need to find the difference between the selling and buying prize of the given stock
All we have to do is to find the maximum difference which is possible and that will be my answer.
#include<bits/stdc++.h>
using namespace std;
int main(){
int prices[] = {2,3,5,4,6,7};
int n = sizeof(prices)/sizeof(prices[0]);
int ans = 0;
int mini = prices[0];
int maxi = prices[0];
for(int i=0;i<prices.size(); i++){
if(prices[i] < mini){
maxi = max(maxi, prices[i]);
ans = max(ans, maxi-mini);
}
}
return ans;
}
That's all for this video
I will see you in the next blog.