面试经典150题——Day7

文章目录

一、题目

121. Best Time to Buy and Sell Stock

You are given an array prices where pricesi 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 <= pricesi <= 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];
    }
};
相关推荐
普马萨特几秒前
搜索核心算法:从召回到排序
算法·搜索引擎
sheeta19981 分钟前
LeetCode 每日一题笔记 日期:2026.05.31 题目:2126. 摧毁小行星
笔记·算法·leetcode
INGNIGHT12 分钟前
984.不含 AAA 或 BBB 的字符串(贪心)
开发语言·算法·leetcode
飞天狗11114 分钟前
2025第十六届蓝桥杯c/c++B组国赛题解
c语言·c++·算法·蓝桥杯
超梦dasgg20 分钟前
Tarjan算法解 强连通分量 & 循环依赖
算法·深度优先·图论
努力努力再努力wz26 分钟前
【Qt入门系列】:QLabel控件详解:从文本显示到图片展示,再到内容布局与伙伴机制
android·开发语言·数据结构·数据库·c++·qt·mysql
散峰而望42 分钟前
【算法练习】算法练习精选:从 Phone numbers 到 Decrease,覆盖字符串、模拟、图论思维题
数据结构·c++·算法·贪心算法·github·动态规划·图论
薇茗1 小时前
【C++】 基础语法篇
c++·c++基础语法
人道领域1 小时前
【LeetCode刷题日记】538.把二叉搜索树转换为累加树
java·开发语言·后端·算法·leetcode
并不喜欢吃鱼1 小时前
从零开始 C++----- 十二【C++ 数据结构】map/set 全解析:从使用到红黑树底层模拟实现
开发语言·数据结构·c++