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]);
}
}
本文探讨了一种算法,通过动态规划解决股票投资问题,找到在给定价格数组中获取最大利润的方法。实现了一个名为Solution的类,利用三天限制交易规则,模拟买卖股票的过程。关键步骤包括初始化、状态转移和结果计算。实例以[1,2,3,0,2]的价格数组展示,输出最大利润为3。
1676

被折叠的 条评论
为什么被折叠?



