面试经典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];
    }
};
相关推荐
我狸才不是赔钱货4 分钟前
AI大模型“战国策”:主流LLM平台简单介绍
c++·人工智能·程序人生·github·llama
无限进步_10 分钟前
【C语言】在矩阵中高效查找数字的算法解析
c语言·开发语言·数据结构·c++·其他·算法·矩阵
小白要加油努力21 分钟前
滑动窗口的典例以及思路阐述
算法
Yupureki30 分钟前
从零开始的C++学习生活 11:二叉搜索树全面解析
c语言·数据结构·c++·学习·visual studio
CoovallyAIHub1 小时前
一夜之间,大模型处理长文本的难题被DeepSeek新模型彻底颠覆!
深度学习·算法·计算机视觉
再睡一夏就好1 小时前
【C++闯关笔记】STL:deque与priority_queue的学习和使用
java·数据结构·c++·笔记·学习·
天选之女wow1 小时前
【代码随想录算法训练营——Day43(Day42周日休息)】动态规划——300.最长递增子序列、674.最长连续递增序列、718.最长重复子数组
算法·leetcode·动态规划
我是华为OD~HR~栗栗呀2 小时前
华为OD-23届考研-测试面经
java·c++·python·华为od·华为·面试·单元测试
敲代码的嘎仔2 小时前
JavaWeb零基础学习Day4——Maven
java·开发语言·学习·算法·maven·javaweb·学习方法
Qt程序员2 小时前
基于原子操作的 C++ 高并发跳表实现
c++·线程·c/c++·原子操作·无锁编程