题目:
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).
Array Greedy链接: http://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
2/18/2017, Java
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 if (prices.length <= 1) return 0; 4 5 boolean hasStock = false; 6 int sumProfit = 0; 7 int min = 0; 8 9 for(int i = 0; i < prices.length - 1; i++) { 10 if (hasStock) { 11 if (prices[i] > prices[i + 1]) { 12 sumProfit += prices[i] - min; 13 hasStock = false; 14 } 15 } else { 16 if (prices[i] < prices[i + 1]) { 17 min = prices[i]; 18 hasStock = true; 19 } 20 } 21 } 22 if (hasStock) sumProfit += prices[prices.length - 1] - min; 23 return sumProfit; 24 } 25 }
别人的思路:
只要计算数组里的升序和就可以了!二刷再做。