ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

最佳买卖股票时间,以C ++解决方案获得最大的利润说明

前开发者教程 十月26,2018
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+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的





      <source class="ljgv7jT"><aside id="vp7QhOr"><dd id="OpkAAkD" class="OB6olXj"><optgroup class="Zxb8r4n"></optgroup></dd></aside></source>