It's the Xinrui Ma

Blog

Tag: Stock

122. Best Time to Buy and Sell Stock II

Posted by in LeetCode on

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. 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 at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Example 2:

Example 3:


 Solution:
A simple one, just add every possible gain in these days, you will have your profit maximum.
Proof: If you buy at Day 1 and hold to sell until Day 3, your profit will be Profit 3
If you buy at Day 1 and sell at day 2, and buy at day 2 and sell at day 3, your profit will be Profit 1 + Profit 2
Profit 1 + Profit 2 > Profit 3
Answer in JavaScript: