@Test publicvoidtest(){ int[] prices = {2,6,1,7}; int res = maxProfit(prices); System.out.println(res); }
publicintmaxProfit(int[] prices){ if (prices.length == 0){ return0; } int n = prices.length; int[] dp = newint[n]; //dp[i]代表到第i天为止最佳收入 int buy = 0; //当前最佳买入日期 for (int i = 1; i < n; i++) { if (prices[i] < prices[buy]){ buy = i; } dp[i] = Math.max(prices[i] - prices[buy], dp[i - 1]); } return dp[n - 1]; } }
经典的动态规划题,跟着3步走就完事儿~
可以优化一下:dp[i]只和dp[i-1]有关,所以可以不用数组而只用一个变量保存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicintmaxProfit(int[] prices){ if (prices.length == 0){ return0; } int n = prices.length; int res = 0; int buy = 0; //当前最佳买入日期 for (int i = 1; i < n; i++) { if (prices[i] < prices[buy]){ buy = i; } res = Math.max(prices[i] - prices[buy], res); } return res; }