💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**一. 题目描述** Say you have an array for which the i-th element is the price of a given stock on day i.  Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). **二. 题目分析** 该题是买卖股票的第二题。题目给出的基本信息没什么变化,与第一题不同的是的,允许进行任意次数的买卖,但必须保证买卖一次后才能进行第二次操作。继续分析会发现,这实际上是求股价数组所有上升段的和。 **三. 示例代码** ~~~ #include <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(vector<int> &prices) { int result = 0; int i = 0; int len = prices.size(); if(len <= 1) return 0; for(i = 1; i < len; ++i) { if (prices[i] > prices[i - 1]) result += prices[i]-prices[i - 1]; } return result; } }; ~~~ **四. 小结** 与该题相关的题目还有好几道。后续更新…