题目
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 BestTimeToBuyAndSellStockII { public int maxProfit(int[] prices) { if (prices == null || prices.length <= 1) { return 0; } int profit = 0; int N = prices.length; int j, i = 0; while (i < N) { // find the valley while (i + 1 < N && prices[i] >= prices[i + 1]) { ++i; } // find the peak j = i + 1; while (j + 1 < N && prices[j] < prices[j + 1]) { ++j; } if (j < N) { profit += prices[j] - prices[i]; } i = j + 1; } return profit; } }代码2
public class BestTimeToBuyAndSellStockII { public int maxProfit(int[] prices) { int profit = 0; for (int i = 0; i < prices.length - 1; i++) { if (prices[i + 1] > prices[i]) { profit += prices[i + 1] - prices[i]; } } return profit; } }
LeetCode | Best Time to Buy and Sell Stock II
原文:http://blog.csdn.net/perfect8886/article/details/19764467