Example 1: Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy 上 day 2 (price = 1) and sell 上 day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.
解决这个问题的方法很简单。
我们采用2个变量,即minPrice和maxProfit。 minPrice从第0天到第i天将具有最低价格,maxProfit从第0天到第i天将具有maxProfit。
从第1天开始,将使用以下公式计算minPrice:
minPrice = min(minPrice, prices[i]);
对于maxProfit,请使用以下公式:
maxProfit = max(maxProfit, prices[i] - minPrice);
最后返回maxProfit。
C ++解决方案:
#include<iostream> #include<vector> using namespace std; int get_max_profit(vector<int> &prices) { int maxProfit = 0; int minPrice = INT_MAX; for(int i = 0; i < prices.size(); i++) { minPrice = min(minPrice, prices[i]); maxProfit = max(maxProfit, prices[i] - minPrice); } return maxProfit; } int main() { vector<int> prices; prices.push_back(7); prices.push_back(1); prices.push_back(5); prices.push_back(3); prices.push_back(6); prices.push_back(4); cout<<"The maximum profit is " << get_max_profit(prices)<<endl; return 0; }
输出:
The maximum profit is 5
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |