/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit = profit + prices[i] - prices[i - 1];
}
}
return profit;
};
C++ Code:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0;
for(int i=1;i<prices.size();i++)
{
if(prices[i] > prices[i-1])
{
res += prices[i] - prices[i-1];
}
}
return res;
}
};
Java Code:
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for(int i=1;i<prices.length;i++)
{
if(prices[i] > prices[i-1])
{
res += prices[i] - prices[i-1];
}
}
return res;
}
}
Python Code:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1, len(prices)):
tmp = prices[i] - prices[i - 1]
if tmp > 0: profit += tmp
return profit
复杂度分析
时间复杂度:$O(N)$
空间复杂度:$O(1)$
相关题目
大家对此有何看法,欢迎给我留言,我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 37K star 啦。 大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。