DP---股票买卖

1.允许多次交易

法一:DP

 1 //允许多次交易
 2     public int maxProfit(int[] prices) {
 3 
 4         int len = prices.length;
 5         int[][] dp = new int[len][2];
 6         dp[0][0] = 0;
 7         dp[0][1] = 0 - prices[0];
 8         for (int i = 1; i < len; i++) {
 9             dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
10             dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
11 
12         }
13 
14         return dp[len - 1][0];
15     }

法二:贪心

2.只允许交易一次

法一:DP

 1  //只允许交易一次
 2     public int maxProfit1(int[] prices) {
 3 
 4         int len = prices.length;
 5         int[][] dp = new int[len][2];
 6         dp[0][0] = 0;
 7         dp[0][1] = 0 - prices[0];
 8         for (int i = 1; i < len; i++) {
 9             dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
10             dp[i][1] = Math.max(dp[i - 1][1], -prices[i]);
11         }
12 
13         return dp[len - 1][0];
14     }

法二:单调栈

 

 

单调栈通常用来解决的问题及用法:

https://blog.csdn.net/weixin_42784951/article/details/88963758

https://blog.csdn.net/lucky52529/article/details/89155694

 1 //单调栈法
 2     public static int maxProfit2(int[] prices) {
 3 
 4         int maxPro = 0;
 5         Stack<Integer> stack = new Stack<>();
 6         int[] arr = Arrays.copyOf(prices, prices.length + 1);
 7         int temp;
 8         int bottom;
 9         for (int i = 0; i < arr.length; i++) {
10 
11             while (!stack.empty() && stack.peek() > arr[i]) {
12                 bottom = stack.firstElement();
13                 temp = stack.pop();
14                 maxPro = Math.max(maxPro, (temp - bottom));
15 
16             }
17             stack.push(arr[i]);
18         }
19 
20         return maxPro;
21     }

 

posted @ 2021-06-28 22:51  L1998  阅读(119)  评论(0)    收藏  举报