Given an array of values which represent prices of an item at different instances of time, compute best buying and selling times (max profit). The timestamps in the array are in chronological order. code example

Example: buy and sell stock gfg

#include <iostream>
using namespace std;

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size()==0 || prices.size()==1)   return 0;
    int minimumvalue=prices[0];
    int maxprofit=0;
        int n=prices.size();
    for(int i=0;i<n;i++)
    {
        if(prices[i]>minimumvalue)
        {
            maxprofit=max(maxprofit,prices[i]-minimumvalue);
        }
        else if(prices[i]<=minimumvalue)
        {
            minimumvalue=prices[i];
        }
    }
   return maxprofit;
    }
};

Tags:

Java Example