122. 买卖股票的最佳时机 II

    科技2022-08-17  117

    方法1 :暴力搜索,但是会超时

    class Solution { private int ans; public int maxProfit(int[] prices) { if(prices.length < 2) return 0; this.ans = 0; dfs(prices,0,0,0,prices.length);//价格,位置,状态,利润 return this.ans; }//判断的结尾在哪?位置截止即是 public void dfs(int []prices,int pos,int status,int profit,int len){ if(len == pos){ this.ans = Math.max(this.ans,profit); return; } //暴力搜索处是选择一种在整个队列里面收益最多的情况,所以必须是在全部结果都找到的情况下,才可以结算,单算一种根本达不到要求 dfs(prices,pos+1,status,profit,len);//不操作 if(status == 0) dfs(prices,pos+1,1,profit-prices[pos],len);// else dfs(prices,pos+1,0,profit+prices[pos],len);// } }

    方法2:贪心算法,贪心是每个局部最优,但是没有一个状态转移的前后影响的特性。

    class Solution { public int maxProfit(int[] prices) { int ans = 0; for(int i = 1; i < prices.length; i++){ int tmp = prices[i] - prices[i-1]; if(tmp > 0) ans += tmp; } return ans; } }

    方法3:动态规划,需要一个状态方程,状态转移,与前后最终的状态。

    class Solution { public int maxProfit(int[] prices) { int len = prices.length; if(len < 2) return 0; int [][]dp = new int[len][2]; dp[0][0] = 0; dp[0][1] = -prices[0]; for(int i = 1; i < len; i++){ dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]); dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0]-prices[i]); } return dp[len-1][0]; } }
    Processed: 0.015, SQL: 9