Leetcode - 121 Best Time to Buy and Sell Stock (Easy)
題目描述:最多交易一次。
解法一:DP
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0;
int[][] mp = new int[prices.length][3];
mp[0][1] = -prices[0];
int res = 0;
for (int i = 1; i < prices.length; i++){
mp[i][0] = mp[i - 1][0]; // 沒有買賣
mp[i][1] = Math.max(mp[i - 1][1], mp[i - 1][0] - prices[i]); // 買了股票
mp[i][2] = mp[i - 1][1] + prices[i]; // 賣了股票
res = Math.max(res, Math.max(mp[i][0], Math.max(mp[i][1], mp[i][2])));
}
return res;
}
解法二:
public int maxProfit(int prices[]) {
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minprice)
minprice = prices[i];
else if (prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
return maxprofit;
}