Problem
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.
Example
Given array [3,2,3,1,2], return 1.
思路
- 买入最低价, 卖出最高价
- 只能在卖出当天或之前买入
- 暴力解法:
- 遍历数组的时候, 当前元素与前面元素的差, 取最大值
- O(n ^ 2) time
- 因为要找当前元素及之前的最小值, 所以每次遍历的时候都记录一个最小值即可

public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int len = prices.length;
int[] min = new int[len];
int max = 0;
min[0] = prices[0];
for (int i = 1; i < len; i++) {
min[i] = Math.min(min[i - 1], prices[i]);
max = Math.max(max, prices[i] - min[i]);
}
return max;
}
空间优化
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int len = prices.length;
int max = 0;
int min = prices[0];
for (int i = 1; i < len; i++) {
min = Math.min(min, prices[i]);
max = Math.max(max, prices[i] - min);
}
return max;
}