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.
public class Solution { public int maxProfit(int[] prices) { // Traverse the array to compare current price with minimum price before the current price. int n = prices.length; if (n <= 1) return 0; // Minimum price before current price int minBfCur = prices[0]; int maxProfit = 0; for (int i = 0; i < n; i++) { maxProfit = Math.max(maxProfit, prices[i]-minBfCur); minBfCur = Math.min(minBfCur, prices[i]); } return maxProfit; } }
No comments:
Post a Comment