算法刷题记录 Day42

算法刷题记录 Day42

Date: 2024.04.09

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

c++ 复制代码
// 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. 卖卖股票的最佳时机

c++ 复制代码
// 贪心
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 小时前
算法-贪婪算法
算法·贪心算法
Evand J2 小时前
MATLAB程序演示与编程思路,相对导航,四个小车的形式,使用集中式扩展卡尔曼滤波(fullyCN-EKF)
人工智能·算法
椰萝Yerosius4 小时前
[题解]2023CCPC黑龙江省赛 - Ethernet
算法·深度优先
IT猿手5 小时前
基于 Q-learning 的城市场景无人机三维路径规划算法研究,可以自定义地图,提供完整MATLAB代码
深度学习·算法·matlab·无人机·强化学习·qlearning·无人机路径规划
竹下为生6 小时前
LeetCode --- 448 周赛
算法·leetcode·职场和发展
未名编程7 小时前
LeetCode 88. 合并两个有序数组 | Python 最简写法 + 实战注释
python·算法·leetcode
Cuit小唐7 小时前
C++ 迭代器模式详解
c++·算法·迭代器模式
2401_858286117 小时前
CD37.【C++ Dev】string类的模拟实现(上)
开发语言·c++·算法
╭⌒心岛初晴7 小时前
JAVA练习题(2) 找素数
java·开发语言·算法·java练习题·判断素数/质数
懒懒小徐7 小时前
2023华为od统一考试B卷【二叉树中序遍历】
数据结构·算法·华为od