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.
这题不能用最大的减最小的,因为sell必须在buy之后。
Trick是扫数组的过程中记录着当前的min price的下标是什么。
public class Solution {
public int maxProfit(int[] prices) {
int minIndex = 0;
int maxProfit = 0;
for(int i = 0; i < prices.length; i++){
if(prices[i] < prices[minIndex])
minIndex = i;
maxProfit = Math.max(prices[i] - prices[minIndex], maxProfit);
}
return maxProfit;
}
}