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 // Start typing your Java solution below 4 // DO NOT write main() function 5 int max = 0; 6 for(int i = 0; i < prices.length - 1; i ++){ 7 max = ((prices[i + 1] - prices[i] > 0) ? (prices[i + 1] - prices[i] + max): max); 8 } 9 return max; 10 } 11 }
posted on 2013-09-11 05:27 Step-BY-Step 阅读(130) 评论(0) 编辑 收藏 举报