LeeCode打卡第三十七天
第一题:买卖股票的最佳时机II(LeeCode第122题):
给你一个整数数组 prices
,其中 prices[i]
表示某支股票第 i
天的价格。在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。返回 你能获得的 最大 利润
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;
}
}
第二题:跳跃游戏(LeeCode第55题):
给你一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个下标,如果可以,返回 true ;否则,返回 false 。
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;
}
}
第三题:跳跃游戏II(Leecode第45题)
给定一个长度为 `n` 的 **0 索引**整数数组 `nums`。初始位置为 `nums[0]`。每个元素 `nums[i]` 表示从索引 `i` 向前跳转的最大长度。换句话说,如果你在 `nums[i]` 处,你可以跳转到任意 `nums[i + j]` 处:
- 0 <= j <= nums[i]
- i + j < n
class Solution {
public int jump(int[] nums) {
int curDistance = 0;
int ans = 0;
int nextDistance = 0;
for(int i = 0; i < nums.length - 1; i++){
nextDistance = Math.max(i + nums[i], nextDistance);
if(i == curDistance){
curDistance = nextDistance;
ans++;
}
}
return ans;
}
}