Say you have an array for which the ith element is the price of a given stock on day i.
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.
Solution1:
时间复杂度O(n), 空间复杂度O(n)
public int maxProfit(int[] prices) {
int n = prices.length;
if(n<=1) return 0;
int[] maxPrice = new int[n];
maxPrice[n-1] = prices[n-1];
for(int i=n-2; i>=0; i--) {
maxPrice[i] = Math.max(prices[i], maxPrice[i+1]);
}
int maxProfit = Integer.MIN_VALUE;
for(int i=0; i<n-1; i++) {
maxProfit = Math.max(maxProfit, maxPrice[i]-prices[i]);
}
return maxProfit;
}
Solution2:
时间复杂度O(n), 空间复杂度O(1)
public int maxProfit(int[] prices) {
int n = prices.length;
if(n<=1) return 0;
int maxProfit = Integer.MIN_VALUE;
int minPrice = prices[0];
for(int i=0; i<n; i++) {
minPrice = Math.min(minPrice, prices[i]);
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
}
return maxProfit;
}