C++中买卖股票后的最大利润
在这个问题中,我们得到一个数组 `stkprice[]`,它表示某只股票在第 i 天的价格。我们的任务是创建一个程序来计算C++中买卖股票后的最大利润。
问题描述 − 在这里,我们需要检查何时可以买卖股票以获得利润。为了获得利润,我们需要以低价买入股票,并在价格上涨时卖出。当价格再次下跌时,重复相同的操作。
让我们来看一个例子来理解这个问题:
输入
stkprice[] = {120, 310, 405, 210, 150, 550}输出
685
解释
第一天买入,第三天卖出,将获得285的利润。
之后,第五天买入,第六天卖出,将获得400的利润。
这使得总利润为(400 + 285) = 685
解决方案方法
一个简单的解决方案是检查所有可能的买卖周期组合。尝试从每一天开始的买卖周期组合到当前的第一天买入最后一天卖出。并选择产生最大利润的周期。
程序说明了我们解决方案的工作原理:
示例
#include <iostream>
using namespace std;
int max(int a, int b){
if(a > b)
return a;
return b;
}
int MaximizeProfit(int stkPrice[], int firstDay, int lastDay){
if (lastDay <= firstDay)
return 0;
int maxProfit = 0;
for (int i = firstDay; i < lastDay; i++) {
for (int j = i + 1; j <= lastDay; j++) {
if (stkPrice[j] > stkPrice[i]) {
int profit = ( stkPrice[j] - stkPrice[i] ) + MaximizeProfit(stkPrice, firstDay, i - 1) + MaximizeProfit(stkPrice, j + 1, lastDay);
maxProfit = max(maxProfit, profit);
}
}
}
return maxProfit;
}
int main(){
int stkPrice[] = { 120, 310, 405, 210, 150, 550 };
int days = 6 ;
cout<<"The Maximum profit is "<<MaximizeProfit(stkPrice, 0, days);
return 0;
}输出
The Maximum profit is 4196007
一个更有效的解决方案是通过为每次交易寻找最大利润来找到它们的总最大利润。这可以通过找到交易日的局部最小值和最大值来完成。局部最小值是指股票价格低于其前一天和后一天的日子。最大值与最小值相反。如果没有局部最小值(在索引 0 到 n-2 之间),则这些天不会有利润。
为了最大化利润,我们将在局部最小值买入股票,在下一个局部最大值卖出,对最小值-最大值对重复此操作。将所有最小值-最大值利润相加,我们将得到 maxProfit。
程序说明了我们解决方案的工作原理:
示例
#include <iostream>
using namespace std;
void MaximizeProfit(int price[], int n){
if (n == 1)
return;
int maxProfit = 0;
int i = 0;
while (i <= n - 1) {
while ((i <= n - 2) && (price[i + 1] <= price[i]))
i++;
int minima = i++;
while ((i < n) && (price[i] >= price[i - 1]))
i++;
int maxima = i - 1;
maxProfit += (price[maxima] - price[minima] );
// For displaying profit for one minima-maxima cycle
//cout <<"Stock bought on day "<<(minima+ 1 )<<" and Sold
on day "<<(maxima+1) <<" at a profit of "<<(price[maxima] - price[minima] )<<"\n";
}
cout<<"The maximized profit is "<<maxProfit;
}
int main(){
int stkPrice[] = { 120, 310, 405, 210, 150, 550 };
int days = 6;
MaximizeProfit(stkPrice, days);
return 0;
}输出
The maximized profit is 685
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP