If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Idea: Scan the array from left to right. For each price, test how much profit can get if sell at current price. Therefore the problem is to cache the lowest price appeared before.
Time: O(n) Space: O(1)
Code:
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null||prices.length<=1)
{
return 0;
}
int lowestBuy=prices[0];
int maxProfit=0;
for(int i=1;i<prices.length;i++)
{
maxProfit=Math.max(maxProfit,prices[i]-lowestBuy);
lowestBuy=Math.min(lowestBuy,prices[i]);
}
return maxProfit;
}
}
No comments:
Post a Comment