面试经典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];
    }
};
相关推荐
ashiho1 小时前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
数据工匠老o1 小时前
数据库没死,业务卡住了:行锁等待、元数据锁、长事务的排查路径
数据库·算法·架构
黑客笔记1 小时前
安全态势感知中的资产失陷排名思考
人工智能·算法·网络安全
爱写Bug的浮游3 小时前
C++移动构造真的比拷贝快吗
c++·性能优化
Aaa西红柿鸡蛋3 小时前
网络协议分析实验:基于 UDP 广播模型的 C/S 通信设计与实现
c++
青少儿编程课堂4 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:扫描线与线段树求矩形面积并解析
c++·python·算法·bfs·信息学竞赛
电科_银尘4 小时前
【大模型算法与工程 09】SGD、Momentum与AdamW:优化器如何选择
人工智能·算法
货拉拉技术6 小时前
视觉底座:货拉拉OCR的进阶之路
算法
__underline__6 小时前
冷门Python知识点005篇:list.sort( )的排序稳定性,是用0字节额外内存实现的
python·算法