309. Best Time to Buy and Sell Stock with Cooldown
1 題目理解
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
2 動態規劃
class Solution {public int maxProfit(int[] prices) {if(prices == null || prices.length == 0) return 0;int n = prices.length;int[][] dp = new int[n][3];dp[0][0] = -prices[0];for(int i=1;i<n;i++){dp[i][0] = Math.max(dp[i-1][2] - prices[i], dp[i-1][0]);dp[i][1] = dp[i-1][0] + prices[i];dp[i][2] = Math.max(dp[i-1][2],dp[i-1][1]);}return Math.max(dp[n-1][1],dp[n-1][2]);} }總結
以上是生活随笔為你收集整理的309. Best Time to Buy and Sell Stock with Cooldown的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [高效时间管理]复盘篇
- 下一篇: 在线常用正则表达式可视化生成与测试工具与