[LeetCode] Best Time to Buy and Sell Stock

本文分享了一个简洁的解决方案,通过5行代码计算股票投资的最大利润。利用动态规划的思想,简化了传统的递归公式,使得计算过程更加高效。代码实现中包括一个类Solution,其中定义了一个函数maxProfit来计算利润。

This post shares a very simple solution, whose code is rewritten below, just 5 lines :-)

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int low = INT_MAX, profit = 0;
 5         for (int price : prices) {
 6             low = min(low, price);
 7             profit = max(profit, price - low);
 8         }
 9         return profit;
10     }
11 };

To give an explanation, suppose we denote p[n] to be the maximum profit we can earn from days 0 to n. Then we have the following DP recursive formula:

p[n + 1] = max(p[n], prices[n + 1] - min_{i = 0, ..., n}prices[i]).

The above code simply computes this formula :-)

转载于:https://www.cnblogs.com/jcliBlogger/p/4548105.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值