Problem
You are given an array containing prices for a share during a day. The index of the array is the time (in minutes) at which the price of the share had the value at that index. Write a function to return the maximum profit you can get. You can buy the share at any point in time and sell it at any point in time.
Solution
int[] price = {-1,10,7,6,2};
public int getMaxProfit() {
int min = price[0], maxProfit =0;
int profit = 0;
for(int i=1; i< price.length; i++) {
if(price[i] < min) min = price[i];
else {
profit = price[i] - min;
if(profit > maxProfit) maxProfit = profit;
}
}
return maxProfit;
}
No comments:
Post a Comment