150. Best Time to Buy and Sell Stock II【medium】

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

 
Example

Given an example [2,1,2,0,1], return 2

解法一:

 1 class Solution {
 2 public:
 3     /**
 4      * @param prices: Given an integer array
 5      * @return: Maximum profit
 6      */
 7     int maxProfit(vector<int> &prices) {
 8         int total = 0;
 9         if (!prices.empty()) {
10             for (int i = 0; i < prices.size() - 1; i++) {
11                 if (prices[i + 1] > prices[i]) {
12                     total += (prices[i + 1] - prices[i]);
13                 }
14             }
15         }
16         return total;
17     }
18 };

greedy的思想,只要是有收益就加上。

参考@NineChapter 的代码

解法二:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         int profit = 0;
 4         for (int i = 0; i < prices.length - 1; i++) {
 5             int diff = prices[i + 1] - prices[i];
 6             if (diff > 0) {
 7                 profit += diff;
 8             }
 9         }
10         return profit;
11     }
12 }

和解法一思路一样,看起来更舒服一些的代码风格。

参考@NineChapter 的代码

原文地址:https://www.cnblogs.com/abc-begin/p/8150556.html