45. 跳跃游戏Ⅱ
解法一:
class Solution {
public int jump(int[] nums) {
int max = 0; //下一次能跳到的最远距离
int step = 0; //记录跳跃次数
int next = 0; //上一次能跳到的最远距离,即边界,如果预测的时候到达这个位置,步数就要+1
//从原点开始跳,预测目前站的地方能跳到的最远范围内的每一个位置,跳到下一次能跳到更远地方的位置,开始下一次预测
for(int i = 0; i < nums.length-1; i ++){
//因为是起跳的时候就+1了,如果最后一次跳跃刚好到达了最后一个位置,那么遍历到最后一个位置的时候就会再次起跳,因此不能遍历最后一个位置
max = max > nums[i]+i ? max : nums[i]+i;
if(i == next){
//预测到达了边界,这时候跳到此时max最大的地方,开始下一次起跳,更新边界,开始下一次预测
next = max;
step ++;
}
}
return step;
}
}
解法二:
class Solution {
public int jump(int[] nums) {
//从最后一个位置往前查找,找到能跳到当前位置的下标最小的地方,即离当前位置最远的地方
int now = nums.length - 1;
int step = 0; //记录步数
while(now > 0){
//从左到右遍历,找到的第一个可以到达当前位置的地方就是最远的地方
for(int i = 0; i < now; i ++){
if(nums[i]+i >= now){
now = i;
step ++;
break;
}
}
}
return step;
}
}
122. 买卖股票的最佳时机Ⅱ
解法一:
class Solution {
public int maxProfit(int[] prices) {
//如果给的天数小于2,就不用买卖了
if(prices.length < 2){
return 0;
}
int max = 0;
//遍历每一天,如果第二天的价格比今天的价格高那么就今天买明天卖,差价就是赚的钱
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1])
max += prices[i] - prices[i - 1];
}
return max;
}
}
解法二:
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length < 2) {
return 0;
}
int[] cash = new int[prices.length]; //保证利润最大时手里的钱
int[] hold = new int[prices.length]; //每天买了股票后手里的钱,即总财产为手里的钱和当天的股票价之和
cash[0] = 0; //第一天没有买股票,持有0
hold[0] = -prices[0]; //第一天买了股票,持有-prices[0]
for (int i = 1; i < prices.length; i++) {
//比较前一天没买股票和前一天买了股票今天卖出的收益高低,选择高的
cash[i] = Math.max(cash[i - 1], hold[i - 1] + prices[i]);
//比较前一天买股票还是今天买股票手里剩的钱的多少,选择多的
hold[i] = Math.max(hold[i - 1], cash[i - 1] - prices[i]);
}
return cash[prices.length - 1];
}
}