LeetCode 122. Best Time to Buy and Sell Stock II

Description

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/

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 (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Explanation

This is a follow-up question for Best Time to Buy and Sell Stock. The difference is that it allows multiple transactions.

A single for loop could solve the problem. If a price is greater than the previous price, add their difference to the maxProfit.

Video Tutorial

Java Solution

One Thought to “LeetCode 122. Best Time to Buy and Sell Stock II”

Leave a Reply

Your email address will not be published. Required fields are marked *