You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
输入 | 输出 |
---|---|
prices = [7,1,5,3,6,4] | 7 |
prices = [1,2,3,4,5] | 4 |
prices = [7,6,4,3,1] | 0 |
IDE:VS2019
IDE版本:16.10.1
语言:c++11
这一题可以借鉴121题的方法,也就是Kadane's Algorithm,具体来说就是求出相邻两个元素间的差值,组成数组,再将数组中的正值加到一起,即可。具体代码如下:
class Solution { public: int maxProfit(vector<int>& prices) { int maxpro = 0; for (int i = 1; i < prices.size(); i++) maxpro += max(0, prices[i] - prices[i - 1]); return maxpro; } };