Here is the solution:
function maxProfit(prices)
profit := 0
for i from 1 to length - 1
if prices[i] > prices[i-1] then
profit := profit + (prices[i] - prices[i-1])
return profit
Time: . Space: .
Every positive difference means profit. If the price goes from to , that is profit. If it then goes to , you do not subtract (you already sold). If it goes from to , that is more profit. Total: .