#include <iostream>
#include <vector>
usingnamespacestd;// returns the maximum profit (or minimum loss) user can make// by buying and selling one item intmax_profit(vector<int>prices){// stores the maximum profit made so farintmaxProfitSoFar=prices[1]-prices[0];// stores the minimum price seen so farintminPriceSoFar=min(prices[0],prices[1]);for(inti=2;i<prices.size();i++){// maximum profit will be the maximum of// (current price - minimum price seen before) and maximum profit so farmaxProfitSoFar=max(prices[i]-minPriceSoFar,maxProfitSoFar);// minimum price will be minimum of// current price and minimum price seen beforeminPriceSoFar=min(prices[i],minPriceSoFar);}returnmaxProfitSoFar;}// main functionintmain(){cout<<max_profit({3,10,8,4})<<"\n";// output -> 7cout<<max_profit({10,7,5,8,11,9})<<"\n";// output -> 6cout<<max_profit({3,4})<<"\n";// output -> 1cout<<max_profit({9,9})<<"\n";// output -> 0cout<<max_profit({10,7,5,4,1})<<"\n";// output -> -1return0;}
For the last case the vector is sorted in descending order. So there is no way user will make any profit. The minimum loss is 1 (i.e. buy the item at price 5 and sell it at price 4).
Remember you have to buy the item first and then sell it.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
C++ solution
How is the last output -1? Shouldn't it be 9?
Here I represented the loss with negative number.
For the last case the vector is sorted in descending order. So there is no way user will make any profit. The minimum loss is 1 (i.e. buy the item at price 5 and sell it at price 4).
Remember you have to buy the item first and then sell it.