classSolution{publicintmaxProfit(int[] prices){// 做啥:找一个i,j(j > i)且prices[j] > prices[i],使得 max = prices[j] - prices[i]// 用dp做吧int len = prices.length;if(len ==1){return0;}// dp[i]代表当前值之后能遇到的最大值int[] dp =newint[len];
dp[len-1]=0;for(int i=len-2;i >=0;i--){
dp[i]=Math.max(prices[i+1],dp[i+1]);}int max =0;for(int i=0;i<len-1;i++){
max =Math.max(dp[i]- prices[i],max);}return max;}}
更新啦~优化代码
节约了空间,空间复杂度由 O(n) 变成了 O(1)
classSolution{publicintmaxProfit(int[] prices){if(prices.length <2){return0;}int len = prices.length;int max = prices[len -1];int ans =0;for(int i = len -2; i >=0; i--){int nowProfit = max - prices[i];// ans 更新if(nowProfit > ans){
ans = nowProfit;}// min 更新if(prices[i]> max){
max = prices[i];}}return ans;}}
再次更新
classSolution{publicintmaxProfit(int[] prices){int max = prices[prices.length -1];int res =0;for(int i = prices.length -2; i >=0; i--){
max =Math.max(max, prices[i +1]);
res =Math.max(max - prices[i], res);}return res;}}
文章目录题目描述代码 & 思路题目描述讲道理,一眼dp代码 & 思路时间复杂度O(n),不过可改进的地方还多,跑出来大概6ms。class Solution { public int maxProfit(int[] prices) { // 做啥:找一个i,j(j > i)且prices[j] > prices[i],使得 max = prices[j] - prices[i] // 用dp做吧 int