/**
* @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