122.Best-Time-to-Buy-and-Sell-Stock-II

122. Best Time to Buy and Sell Stock II

题目地址

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

https://www.lintcode.com/problem/best-time-to-buy-and-sell-stock-ii/description

题目描述

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;
  }
}

Last updated