int len = prices.length; int res = 0; int buyInCost = prices[0]; for (int i = 1; i < len; i++) { buyInCost = Math.min(buyInCost, prices[i]); res = Math.max(res, prices[i]-buyInCost); } return res; }
publicintmaxProfit2(int[] prices){ if(prices==null || prices.length==0) return0; int len = prices.length; int[] dp = newint[len]; // 前i个日最大利润 dp[0]=0; int minValue = prices[0]; for (int i = 1; i < len; i++) { minValue = Math.min(minValue, prices[i]); dp[i] = Math.max(dp[i-1], prices[i]-minValue); } return dp[len-1]; }