算法刷题记录 Day42

本文介绍了两种解决LeetCode题目122和121(买卖股票的最佳时机)的方法:一种是使用动态规划,通过计算每个交易日可能的最大利润;另一种是贪心策略,寻找连续上涨时的利润。
摘要由CSDN通过智能技术生成

算法刷题记录 Day42

Date: 2024.04.09

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

// dp
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if(n == 1)  return 0;
        // dp[i]表示第i天的最大利润;
        // dp[i] = dp[i-1] + max(prices[i]-prices[i-1], 0);
        vector<int> dp(n, 0);
        for(int i=1; i<n; i++){
            dp[i] = dp[i-1] + max(prices[i]-prices[i-1], 0);
        }
        return dp[n-1];
    }
};

// 贪心
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        // 只要比昨天涨了,昨天就买,今天就卖
        for(int i=1; i<prices.size(); i++){
            if(prices[i] > prices[i-1])
                res += (prices[i] - prices[i-1]);
        }
        return res;
    }
};

lc 121. 卖卖股票的最佳时机

// 贪心
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        // 取后项-前项中的最大值。1.暴力ON^2.
        // 2.从左往右遍历。记录当前的最小值和当前值减去最小值的大小;
        // 3. dp[i] 表示在前i天中完成买入和卖出的最大利润;
        // dp[i] = 
        int n = prices.size();
        
        int cur_min = INT_MAX;
        int cur_res = 0;

        for(int i=0; i<n; i++){
            if(i > 0)
                cur_res = max(cur_res, prices[i] - cur_min);
            cur_min = min(prices[i], cur_min);
        }
        return cur_res;

    }
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值