题目:只能对一支股票进行一次交易,即一次购入和一次卖出,求最大收益
思路:找到prices[n]左半部分最小的值,右半部分最大的值,求差值
public class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0; //O(n)
if(prices.length == 0) //prices == null, judge failing,doubting prices = new int[0]
return 0;
int leftMin = prices[0];
for(int i = 0; i < prices.length; i++){
maxProfit = Math.max(maxProfit, prices[i] - leftMin);
leftMin = (prices[i] < leftMin) ? prices[i] : leftMin;
}
return maxProfit;
}
}