面试经典150题——Day7

文章目录

一、题目

121. Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]

Output: 5

Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]

Output: 0

Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

1 <= prices.length <= 105

0 <= prices[i] <= 104

题目来源:leetcode

二、题解

使用动态规划的思想,避免双重for循环,在O(n)时间内解决问题

cpp 复制代码
class Solution {
public:
    int max(int a,int b){
        if(a > b) return a;
        else return b;
    }
    int maxProfit(vector<int>& prices) {
        const int N = 100010;
        int n = prices.size();
        int dp[N];
        dp[0] = 0;
        int minVal = prices[0];
        for(int i = 1;i < n;i++){
            if(prices[i] < minVal) minVal = prices[i];
            dp[i] = max(prices[i] - minVal,dp[i-1]);
        }
        return dp[n-1];
    }
};
相关推荐
行然梦实13 分钟前
论文阅读:《多目标和多目标优化的回顾与评估:方法和算法》
论文阅读·算法·机器学习·数学建模
castro20 分钟前
斐波那契堆:理论强者与现实挑战——深入解析高效优先队列的实现与局限
算法
go546315846524 分钟前
离散扩散模型在数独问题上的复现与应用
线性代数·算法·yolo·生成对抗网络·矩阵
惜鸟29 分钟前
PDF页眉页脚识别与去除方案
后端·算法
程序员编程指南39 分钟前
Qt 移动应用常见问题与解决方案
c语言·开发语言·c++·qt
kebeiovo1 小时前
C++代码题部分(1)
开发语言·c++
设计师小聂!1 小时前
力扣热题100-------74.搜索二维矩阵
算法·leetcode·矩阵
tomato091 小时前
河南萌新联赛2025第(二)场:河南农业大学(补题)
开发语言·c++
小O的算法实验室2 小时前
2025年ESWA SCI1区TOP,强化学习多目标灰狼算法MOGWO-RL+分布式混合流水车间调度,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
菥菥爱嘻嘻2 小时前
力扣面试150(44/150)
javascript·leetcode·面试