以下是本人的C++算法学习笔记,记录在博客上以供自己随时查阅
题目描述:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
参照网上各位算法大牛的文章,该算法比较好的解题思路是计算上升期的价格总和
我先在VS2017上整体实现该功能,再将关键代码在LeetCode上执行
C++实现如下:
int maxProfit(vector<int>& prices)
{
int benift = 0;
int i = 0, j = 1;
while (j < prices.size())
{
if (prices[j] > prices[i])
{
benift += prices[j] - prices[i];
}
i++;
j++;
}
return benift;
}
int main()
{
int a[] = { 7,1,5,3,6,4 };
int b[] = { 7,6,4,3,1 };
vector<int> prices_a(a, a + 6);
vector<int> prices_b(b, b + 5);
int benift_a = maxProfit(prices_a);
int benift_b = maxProfit(prices_b);
cout << "max profit of a: " << benift_a << endl;
cout << "max profit of b: " << benift_b << endl;
system("pause");
return 0;
}