Description:
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).
Solution:
Time Complexity : O(n)
Space Complexity: O(1)
var maxProfit = function(prices) {
let maxprofit = 0;
for (let i = 1; i < prices.length; i++) {
// Add to the max profit total if the current price is greater than previous
// We "sell" when the the opposite is true because we will not buy on days that dip.
if (prices[i] > prices[i - 1])
// Add the increse in price to our profit
maxprofit += prices[i] - prices[i - 1];
}
return maxprofit;
};
Top comments (7)
A working solution from the one non-working above (JAVASCRIPT):
NOTE: on line 3 and line 6 I didn't write "let" to declare a variable, because I declared one prior to it so I didn't need to use "let" again, but for clarification you can use the "let" keyword and it will work the same.
Original post is valid I have tested it.
I found that solution is very popular and helpful : youtube.com/watch?v=HOLeZ5ct2h4
You refer to Java youtube solution on a topic of javascript , whats wrong with this post...
Are u a pseudo-coder and not real developer, or a developer who knows both java and javascript so u mistaken it one for the other ? Like how otherwise?!
This code is unfinished nor is it giving the correct output?
What was the purpose of this post, have u tested it urself?