面试经典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];
    }
};
相关推荐
苏辰澈7 分钟前
C++自己的族谱规则:继承详解下
c语言·开发语言·c++·visualstudio
圣保罗的大教堂42 分钟前
leetcode 3302. 字典序最小的合法序列 中等
leetcode
驭渊的小故事1 小时前
NC229023 题解:二分答案求解“最大化最小值“问题
java·算法
朝朝辞暮i1 小时前
C++ 第 36 课:Action——机械臂/VLA 非常重要
开发语言·c++·算法·ros2
无名猿1 小时前
锁进阶:atomic_flag 自旋锁、shared_mutex 读写锁与无锁的代价
c++·性能优化·并发编程·现代c++
ra90fy1 小时前
B3873 [GESP202309 六级] 小杨买饮料
c++·算法
尘客-追梦1 小时前
qmake / jom / 影子构建:把编译管起来
开发语言·c++·qt
Omics Pro1 小时前
北理工李荣华:AI虚拟细胞证据多模态推理基准
数据库·人工智能·算法·机器学习·自然语言处理
Cccp.1231 小时前
【leetcode】(九)哈希函数与哈希表
数据结构·leetcode·哈希算法
xieliyu.1 小时前
LeetCode 1419 数青蛙:状态模拟求最少青蛙数量|Java 题解
java·算法·leetcode