欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

代码随机化、第 32 天、购买股票的时机、跳跃游戏及其他问题

最编程 2024-04-27 22:14:22
...

122.买股票的时机

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;
    }
};

思路:将利润平分的每俩天的利润之和,因为每一天既可以买股票,又可以卖股票,要想收获利润最少是第二开始

55.跳跃游戏

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;
    }
};

这道是,只要你能够到达最后的终点,随便你这么跳都是可以的

45.跳跃游戏||

这道题要求的是最少的步骤跳到终点,那么就不可以随意的跳动自己的步数,要根据覆盖范围是否能到达最后的终点,而进一步来决定

class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.size()==1) return 0;
        int cur = 0;//当前的范围
        int next = 0;//下一步的范围
        int ans = 0;//记录几走的步数
        for(int i=0;i<nums.size();i++)
        {
            next = max(i+nums[i],next);//下一步的范围
            if(i==cur)
            {
                if(cur!=nums.size()-1)
                {
                    ans++;//走起来
                    cur = next;
                    if(cur>=nums.size()-1)
                    {
                        break;
                    }
                }
            }
        }
        return ans;
    }
};