122. 买卖股票的最佳时机 II
题目链接:122. 买卖股票的最佳时机 II
思路: 收集每天的正利润:从第二天开始,今天的价格减去昨天的价格,如果 >0,加入result,这样最后result的值就是最大的利润。
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
for (int i = 1; i < prices.length; i++) {
result += Math.max(prices[i] - prices[i - 1], 0);
}
return result;
}
}
55. 跳跃游戏
题目链接:55. 跳跃游戏
思路: 每到一步,更新能到达的最远距离,如果最远距离 >= 数组最后一位的位置,返回true,否则返回false。
class Solution {
public boolean canJump(int[] nums) {
if (nums.length == 1) {
return true;
}
int jump = 0;
for (int i = 0; i <= jump; i++) {
jump = Math.max(jump, i + nums[i]);
if (jump >= nums.length - 1) {
return true;
}
}
return false;
}
}
45. 跳跃游戏 II
题目链接:45. 跳跃游戏 II
思路:
只需要判断哪一个选择最具有「潜力」即可:i 和 end 标记了可以选择的跳跃步数,farthest 标记了所有选择 [i..end] 中能够跳到的最远距离,jumps 记录了跳跃次数
class Solution {
public int jump(int[] nums) {
int jump = 0;
int farthest = 0;
int end = 0;
for (int i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);
if (i == end) {
jump++;
end = farthest;
}
}
return jump;
}
}