https://leetcode.com/problems/best-time-to-buy-and-sell-stock/#/description
股票买入和卖出的最大差价,只允许交易一次,实际上就是计算数组中靠后的值和靠前的值最大差。
public class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
if(prices.length == 0)
return 0;
int low = prices[0];
for(int i = 1;i < prices.length;i ++){
if(prices[i] < low){
low = prices[i];
}
else if(prices[i] - low > profit){
profit = prices[i] - low;
}
}
return profit;
}
}
看了一下讨论区,题目可以变形成,如果input是前后两个数字的差,比如输入由{1, 7, 4, 11}变成{0, 6, -3, 7},这道题就转换成maximum subarray(第53题).
逻辑上,题目的思路就变成了,求由前后两个数字差形成的新数组的最大子数列和。如果这个和小于0,则返回0.
public int maxProfit(int[] prices) {
int maxCur = 0, maxSoFar = 0;
for(int i = 1; i < prices.length; i++) {
maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]);
maxSoFar = Math.max(maxCur, maxSoFar);
}
return maxSoFar;
}
maxCur:最大值;maxSoFar:当前最大值