算法刷题记录 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;

    }
};
相关推荐
仍然.1 天前
算法题目---哈希表
数据结构·散列表
QuZero1 天前
ReentrantReadWriteLock mechanism
java·后端·算法
Morwit1 天前
【力扣hot100】 494. 目标和
数据结构·算法·leetcode
handler011 天前
算法:图的基本概念
c语言·开发语言·c++·笔记·算法·图论
科研前沿1 天前
像素即坐标・室外无边界:2026 最新无感定位技术,驱动数字孪生实景可控—— 镜像视界技术白皮书
大数据·人工智能·算法·重构·空间计算
少许极端1 天前
算法奇妙屋(五十)-二分与双指针的结合 + 2024秦皇岛-Problem D
算法·二分+双指针
love在水一方1 天前
【Voxel-SLAM】 体素地图与Bundle Adjustment算法深度分析(四)
人工智能·算法·机器学习
木木_王1 天前
嵌入式Linux学习 | 数据结构 (Day03)顺序表与单链表 超详细解析(含 C 语言实现 + 作业 + 避坑指南)
linux·c语言·数据结构·学习
阿Y加油吧1 天前
二刷 LeetCode:198. 打家劫舍 & 279. 完全平方数 复盘笔记
笔记·算法·leetcode
承渊政道1 天前
【动态规划算法】(子序列问题解题框架与典型案例)
数据结构·c++·学习·算法·leetcode·macos·动态规划