package LeetCode.greedypart02;
/**
* 122. 买卖股票的最佳时机 II
* 给你一个整数数组 prices ,其中prices[i] 表示某支股票第 i 天的价格。
* 在每一天,你可以决定是否购买和/或出售股票。
* 你在任何时候最多只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
* 返回 你能获得的 最大 利润。
* 示例:
* 输入:prices = [7,1,5,3,6,4]
* 输出:7
* 解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
* 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。
* 总利润为 4 + 3 = 7。
* */
/**
* 思路:
* 现在只有一支股票,当前只有买股票或者卖股票的操作
* 选一个低的买入然后选择高的卖,再选低的买再卖,循环往复
* 局部最优:收集每天的正利润,全局最优:求得最大利润
* 这道题目还可以用动态规划来解决
* */
public class BestTimeToBuyAndSellStockII_122 {
public static void main(String[] args) {
int [] prices = {7,1,5,3,6,4};
int result = maxProfit(prices);
System.out.println(result);
}
// 贪心思路
public static 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;
}
}
package LeetCode.greedypart02;
/**
* 55. 跳跃游戏
* 给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。
* 数组中的每个元素代表你在该位置可以跳跃的最大长度。
* 判断你是否能够到达最后一个下标。
* 示例:
* 输入:nums = [2,3,1,1,4]
* 输出:true
* 解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
* */
/**
* 这个问题可以转换为 跳跃覆盖范围可不可以覆盖到终点
* 每次移动取最大跳跃步数,每移动一个单位,就更新最大覆盖范围
* 贪心算法局部最优解:每次取最大跳跃步数(取最大覆盖范围),整体最优解:最后得到整体最大覆盖范围,看是否能到终点。
* */
public class JumpGame_55 {
public static void main(String[] args) {
int [] nums = {2,3,1,1,4};
boolean flag = canJump(nums);
System.out.println(flag);
}
public static boolean canJump(int[] nums) {
if (nums.length == 1) {
return true;
}
//覆盖范围, 初始覆盖范围应该是0,因为下面的迭代是从下标0开始的
int coverRange = 0;
//在覆盖范围内更新最大的覆盖范围
for (int i = 0; i <= coverRange; i++) {
coverRange = Math.max(coverRange, i + nums[i]);
if (coverRange >= nums.length - 1) {
return true;
}
}
return false;
}
}
package LeetCode.greedypart02;
/**
* 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]。
* 示例:
* 输入: nums = [2,3,1,1,4]
* 输出: 2
* 解释: 跳到最后一个位置的最小跳跃数是 2。
* 从下标为 0 跳到下标为 1 的位置,跳1步,然后跳3步到达数组的最后一个位置。
* */
/**
* 思路:
* 和跳跃游戏思路相似,还是要看最大覆盖范围
* 本题是计算最小步数,那么就要想清楚什么时候步数才一定要加一
* 如果当前最大范围到不了,那就需要步数加1,再看最大覆盖能不能到终点
* 这里需要统计两个范围,当前这一步的最大覆盖和下一步的最大覆盖
* */
public class JumpGameII_45 {
public static void main(String[] args) {
int [] nums = {2,3,1,1,4};
int result = jump(nums);
System.out.println(result);
}
public static int jump(int[] nums) {
if (nums == null || nums.length == 0 || nums.length == 1) {
return 0;
}
//记录跳跃的次数
int count=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){
count++;
break;
}
//走到当前覆盖的最大区域时,更新下一步可达的最大区域
if (i==curDistance){
curDistance = maxDistance;
count++;
}
}
return count;
}
}