Given [ (02:00, 7.5), (03:30, 7.9), (04:00, 8.0), (05:30, 6.8), (10:00, 9.01)] times and selling price we need to find the best time for buying and selling to maximize the profit. // times are in increasing order // Sample Output: Buy at 05:30 and sell at 10:00 for a profit of 2.21
I have written the logic to find the max profit but I also need to find the best buying and selling time, so I am bit stuck there
double profit(double prices[])
{
double maxprofit=0;
for(int i=0;i<price.length;i++)
{
double min= values[i];
for(int j=i+1;j<price.length;j++)
{
if(price[j]<price[min])
min=values[min];
}
profit=values[i]-min;
if(maxprofit<profit)
maxprofit=profit;
else
continue;
}
There is no need to use a nested loop, there is a linear time algorithm that can solve this problem.
There is a very detailed explanation of the algorithm here.
Here is how you could fix your code:
public double maxProfit(double[] prices) {
if (prices.length <= 1) return 0;
double minPrice = prices[0];
double maxSoFar = Integer.MIN_VALUE;
double profitSoFar = Integer.MIN_VALUE;
for (int i = 1; i < prices.length; i++){
profitSoFar = prices[i] - minPrice;
minPrice = Math.min(minPrice, prices[i]);
maxSoFar = Math.max(profitSoFar, maxSoFar);
}
return Math.max(maxSoFar, 0);
}