Leetcode 122.买卖股票的最佳时机II
题目链接
思路:贪心算法,算出每两天的利润,将每两天的正利润相加,则为最大利润
代码:
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;
}
}
Leetcode 55. 跳跃游戏
题目链接
思路:贪心算法
代码:
class Solution {
public boolean canJump(int[] nums) {
// 贪心算法
if (nums.length == 1) {
return true;
}
int cover = 0;
for (int i = 0; i <= cover; i++) {
cover = Math.max(i + nums[i], cover);
if (cover >= nums.length - 1) {
return true;
}
}
return false;
}
}
Leetcode 45.跳跃游戏II
题目链接
思路:贪心算法
代码:
class Solution {
public int jump(int[] nums) {
if (nums == null || nums.length == 0 || nums.length == 1) {
return 0;
}
// 记录跳跃的次数
int count = 0;
// 当前覆盖最远距离下标
int curDistance = 0;
// 下一步覆盖最远距离下标
int nextDistance = 0;
for (int i = 0; i < nums.length; i++) {
// 更新下一步覆盖最远距离下标
nextDistance = Math.max(nums[i] + i, nextDistance);
// 遇到当前覆盖最远距离下标
if (i == curDistance) {
// 如果当前覆盖最远距离下标不是终点
if (curDistance != nums.length - 1) {
count++;
// 更新当前覆盖最远距离下标
curDistance = nextDistance;
// 下一步的覆盖范围已经可以达到终点,结束循环
if (nextDistance >= nums.length - 1) {
break;
}
} else {
// 当前覆盖最远距离下标是集合终点,不用做ans++操作了,直接结束
break;
}
}
}
return count;
}
}