给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
对题目进行理解,都有什么情况。分三类:
①数据出现起伏,有高有低。例A=[7,1,5,3,6,4]
②数据递增。例B=[1,2,3,4,5]
③数据递减。例C=[7,6,4,3,1]
对于第一种情况,按照时间顺序,我们要考虑什么时候是低点,买入,什么时候是高点,卖出。第二天低点买入,第三天高点卖出(5-1=4)。允许多次买卖,第四天买入,第五天卖出(6-3=3)。3+4=7,是已知最高。只能单买单卖,不能并行
第二种第三种比较简单,5-1=4/7-1=6
1.先写一个类Solution,方便调用
class Solution {
public:
int maxProfit(vector& prices)
{
int res = 0, n = prices.size();
for (int i = 0; i < n - 1; ++i)
{
if (prices[i] < prices[i + 1])
{
res += prices[i + 1] - prices[i];
}
}
return res;
}
};
分析:遍历完整个数组后即可求得最大利润。n为Vector的长度,用for循环进行遍历,从第一个数开始判断,比如数组A=[7,1,5,3,6,4],7>1,则不进行if判定如下:
if (prices[i] < prices[i + 1])
{
res += prices[i + 1] - prices[i];
}
继续for循环第二个数,1<5,进入if函数,res=5-1=4;按照这个方法遍历整个数组,便可以
2.补全头文件
#include
#include
using namespace std;
3.补全主函数
int main()
{
vector A = { 7,1,5,3,6,4};
Solution pt;
int R=pt.maxProfit(A);
cout << R << endl;
}
#include
#include
using namespace std;
class Solution {
public:
int maxProfit(vector& prices)
{
int res = 0, n = prices.size();
for (int i = 0; i < n - 1; ++i)
{
if (prices[i] < prices[i + 1])
{
res += prices[i + 1] - prices[i];
}
}
return res;
}
};
int main()
{
vector A = { 7,1,5,3,6,4};
Solution pt;
int R=pt.maxProfit(A);
cout << R << endl;
}