题目列表
解题过程
1、122.买卖股票的最佳时机II
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候最多只能持有一股股票。你也可以先购买,然后在同一天出售。
返回你能获得的最大利润。
思路: 分解最终利润。
假如第0天买入,第3天卖出,那么利润为:prices[3] - prices[0]。
相当于(prices[3] - prices[2]) + (prices[2] - prices[1]) + (prices[1] - prices[0])。
此时就是把利润分解为每天为单位的维度,而不是从0天到第3天整体去考虑!
那么根据prices可以得到每天的利润序列:(prices[i] - prices[i - 1]).....(prices[1] - prices[0])。
因此,我们只需要收集正利润的区间,就是股票买卖的区间,而我们只需要关注最终利润,不需要记录区间。
局部最优:收集每天的正利润,全局最优:求得最大利润。
贪心法
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for (int i = 1; i < prices.length; i++) {
res += Math.max(prices[i] - prices[i - 1], 0);
}
return res;
}
}
动态规划
class Solution {
public int maxProfit(int[] prices) {
// [天数][是否持有股票]
int[][] dp = new int[prices.length][2];
// base case
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < prices.length; i++) {
// dp公式
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[prices.length - 1][0];
}
}
2、55.跳跃游戏
给定一个非负整数数组 nums
,你最初位于数组的 第一个下标 。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
思路: 将问题转化为跳跃覆盖范围究竟可不可以覆盖到终点。
每次移动取最大跳跃步数(得到最大的覆盖范围),每移动一个单位,就更新最大覆盖范围。
贪心算法局部最优解: 每次取最大跳跃步数(取最大覆盖范围)。
整体最优解: 最后得到整体最大覆盖范围,看是否能到终点。
class Solution {
public boolean canJump(int[] nums) {
if (nums.length == 1) {
return true;
}
// 当前覆盖的最远距离下标
int end = 0;
// 更新覆盖范围
for (int i = 0; i <= end; i++) {
end = Math.max(end, i + nums[i]);
if (end >= nums.length - 1) {
return true;
}
}
return false;
}
}
3、45.跳跃游戏II
给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。
每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:
- 0 <= j <= nums[i]
- i + j < n
返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]。
思路: 以最小的步数增加覆盖范围,覆盖范围一旦覆盖了终点,得到的就是最小步数!
如果移动下标达到了当前这一步的最大覆盖最远距离了,还没有到终点的话,那么就必须再走一步来增加覆盖范围,直到覆盖范围覆盖了终点。
当移动下标达到了当前覆盖的最远距离下标时
- 如果当前覆盖最远距离下标不是是集合终点,步数就加一,还需要继续走。
- 如果当前覆盖最远距离下标就是是集合终点,步数不用加一,因为不能再往后走了。
// 版本一
class Solution {
public int jump(int[] nums) {
if (nums == null || nums.length == 0 || nums.length == 1) {
return 0;
}
// 结果
int res = 0;
// 当前覆盖最大区域
int curDistance = 0;
// 最大的覆盖区域
int maxDistance = 0;
for (int i = 0; i < nums.length; i++) {
// 在可覆盖区域内更新最大的覆盖区域
maxDistance = Math.max(maxDistance, i + nums[i]);
// 当前一步,再跳一步就到达末尾
if (maxDistance >= nums.length - 1) {
res++;
break;
}
// 走到当前覆盖的最大区域时,更新下一步可达的最大区域
if (i == curDistance) {
curDistance = maxDistance;
res++;
}
}
return res;
}
}
// 版本二
class Solution {
public int jump(int[] nums) {
// 答案
int res = 0;
// 当前覆盖的最远距离下标
int end = 0;
// 下一步覆盖的最远距离下标
int temp = 0;
for (int i = 0; i <= end && end < nums.length - 1; i++) {
temp = Math.max(temp, i + nums[i]);
// 要跳下一步了
if (i == end) {
end = temp;
res++;
}
}
return res;
}
}
总结
今天的题比昨天难了点。