Comment on page


122. Best Time to Buy and Sell Stock II



Given an array prices, which represents the price of a stock in each day.
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, if you already have the stock, you must sell it before you buy again).
Design an algorithm to find the maximum profit.


Approach #1 Sum diff

public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) return 0;
int profit = 0;
for (int i = 1; i < prices.length; i++) {
int diff = prices[i] - prices[i - 1];
if (diff > 0) profit += diff;
return profit;