1. 最佳买卖股票时机含冷冻期
算法思路
分为四个状态:
1. 持有股票的状态
2. 保持不持有股票的状态;
3. 当天卖掉股票的状态;
4. 冷冻期。
注意点
1. 由于冷冻期是在卖掉股票的后一天,所以需要单独列出卖掉股票那一天的状态;
2. 保持不持有股票的状态 = 前一天不持有股票 + 前一天是冷冻期;
3. 三个数相比时,要用两个max函数;
4. 当初始化变量不合法时,可以将变量具体代入递归公式中,设定合理的初始值。
代码
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0;
int[][] dp = new int[prices.length][4];
dp[0][0] = -prices[0];
dp[0][1] = 0;
dp[0][2] = 0;
dp[0][3] = 0;
for(int i = 1; i<prices.length; i++){
dp[i][0] = Math.max(dp[i-1][0], Math.max(dp[i-1][1]-prices[i], dp[i-1][3]-prices[i]));
dp[i][1] = Math.max(dp[i-1][1], dp[i-1][3]);
dp[i][2] = dp[i-1][0] + prices[i];
dp[i][3] = dp[i-1][2];
}
return Math.max(dp[prices.length-1][1], Math.max(dp[prices.length-1][2], dp[prices.length-1][3]));
}
}
2. 买卖股票的最佳时机含手续费
算法思路
与买卖股票Ⅱ类似,只是卖出股票后需要减去手续费。
注意点
代码
class Solution {
public int maxProfit(int[] prices, int fee) {
if(prices == null || prices.length == 0) return 0;
int[][] dp = new int[prices.length][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for(int i = 1; i<prices.length; i++){
dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]);
dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i] - fee);
}
return dp[prices.length-1][0];
}
}
3. 最长递增子序列
算法思路
采用双层循环,设定j<i,若nums[j] 小于nums[i],那么dp[i]就反复在dp[j]+1中更新最大长度。
注意点
1. 因为以nums[i]结尾的最小长度为1,所以dp数组应该初始化为1;
2. 因为数组长度为1时不进入循环,所以应该考虑该特殊的情况。
代码
class Solution {
public int lengthOfLIS(int[] nums) {
if(nums == null) return 0;
if(nums.length<=1) return nums.length;
int[] dp = new int[nums.length];
Arrays.fill(dp,1);
int result = 0;
for(int i = 1; i<nums.length; i++){
for(int j = 0; j<i; j++){
if(nums[i] > nums[j]){
dp[i] = Math.max(dp[i], dp[j]+1);
}
}
result = Math.max(result, dp[i]);
}
return result;
}
}
4. 最长连续递增序列
算法思路
因为本题要求连续递增子序列,所以就只要比较nums[i]与nums[i - 1],而不用去比较nums[j]与nums[i] (j是在0到i之间遍历)。
注意点
1. 上题需要在多个子序列之间取最大长度,所以要取max;
2. 本题不取max是因为:当我们从左到右遍历数组时,如果 nums[i ] > nums[i-1],这意味着可以将 nums[i + 1] 接到以 nums[i] 结尾的连续递增子序列后面,从而形成一个更长的连续递增子序列。因为是连续递增子序列,对于每个位置 i + 1,它的连续递增子序列长度只依赖于其前一个位置 i 的连续递增子序列长度(前提是满足递增条件),所以不需要取 max。
代码
class Solution {
public int findLengthOfLCIS(int[] nums) {
if(nums == null) return 0;
if(nums.length <= 1) return nums.length;
int[] dp = new int[nums.length];
Arrays.fill(dp,1);
int result = 0;
for(int i=1; i<nums.length; i++){
if(nums[i]>nums[i-1]){
dp[i] = dp[i-1]+1;
}
result = Math.max(dp[i],result);
}
return result;
}
}