[LeetCode] Best Time to Buy and Sell Stock
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 :-)
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步