LeetCode122:買賣股票的最佳時機 II(動態規劃)
阿新 • • 發佈:2018-12-24
動態規劃:
1.class Solution { public int maxProfit(int[] prices) { int[] profit = new int[prices.length]; if(prices.length==0) return 0; for (int i = 0; i < prices.length; i++) for (int j = 0; j < i; j++) profit[i] = Math.max(profit[j] + prices[i] - prices[j], profit[i - 1]); return profit[prices.length-1]; } } 2.class Solution { public int maxProfit(int[] prices) { int[] profit = new int[prices.length]; if(prices.length==0) return 0; for (int i = 1; i < prices.length; i++) profit[i] = Math.max(profit[i - 1] + prices[i] - prices[i - 1], profit[i - 1]); return profit[prices.length-1]; } }
這題有點怪,我的理解好像有點出錯
public class MaxProfit122 { public static void main(String[] args) { int[] prices = { 7, 1, 5, 3, 6, 7 }; if (prices.length < 2) System.out.println(0); int sum = 0; for (int i = 0; i < prices.length - 1; i++) if (prices[i + 1] - prices[i] > 0) sum += prices[i + 1] - prices[i]; System.out.println(sum); } }