代码随想录算法训练营第三十二天|122.买卖股票的最佳时机II 55. 跳跃游戏 45.跳跃游戏II

目录

LeeCode 122.买卖股票的最佳时机II

LeeCode 55. 跳跃游戏

LeeCode 45.跳跃游戏II


LeeCode 122.买卖股票的最佳时机II

122. 买卖股票的最佳时机 II - 力扣(LeetCode)

思路:把整体利润拆为每天的利润。

局部最优:收集每天的正利润,全局最优:求得最大利润。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
    	int result = 0;
		for (int i = 1; i < prices.size(); i++) {
			result += max(prices[i] - prices[i - 1] , 0);
		} 
		return result;
    }
};

时间复杂度:O(n)                          空间复杂度:O(1)


LeeCode 55. 跳跃游戏

55. 跳跃游戏 - 力扣(LeetCode)

思路:将题目要求转化为跳跃覆盖范围有没有到达终点。

局部最优解:每次取最大跳跃步数(取最大覆盖范围),整体最优解:最后得到整体最大覆盖范围,看是否能到终点。

class Solution {
public:
    bool canJump(vector<int>& nums) {
    	int cover = 0;
    	if (nums.size() == 1) return true;
    	for (int i = 0; i <= cover; i++) {
    		cover = max(i + nums[i], cover);
    		if (cover >= nums.size() - 1) return true;
		}
		return false;
    }
};

LeeCode 45.跳跃游戏II

45. 跳跃游戏 II - 力扣(LeetCode)

思路:以最小的步数增加最大的覆盖范围,直到覆盖范围覆盖了终点。

class Solution {
public:
    int jump(vector<int>& nums) {
    	if (nums.size() == 1) return 0;
		int curDistance = 0;
		int ans = 0;
		int nextDistance = 0;
		for (int i = 0; i < nums.size() - 1; i++) {
			nextDistance = max(nums[i] + i, nextDistance);
			if (i == curDistance) {
				ans++;
				curDistance = nextDistance;
			}
		} 
    return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_74976519/article/details/130789636
今日推荐