Best Time to Buy and Sell Stock II

Link:http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

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).

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         // special case, if there is no element in the array
 4         // we will fail to get pre;
 5         if (prices.length < 1)
 6             return 0;
 7         // previous price
 8         int pre = prices[0];
 9         int profit = 0;
10         for (int i = 0; i < prices.length; i++) {
11             if (prices[i] > pre) {
12                 // notice how this is calculated.
13                 profit += prices[i] - pre;
14             }
15             // buy today's stock
16             pre = prices[i];
17         }
18         return profit;
19     }
20 
21 }
原文地址:https://www.cnblogs.com/Altaszzz/p/3708334.html