码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ 122. Best Time to Buy and Sell Stock II

时间:2016-05-21 11:29:59      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

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

【思路】

相比较上一个题目,这个题目对交易放松了限制,可以做多笔交易,但是在进行下一笔交易之前必须先完成上一笔交易,而且相同交易只能做一次。我的思路是:如果价格在未来上涨,那么我就在当前买入。如果价格在未来下跌,我就在当前卖出。这样的结果就是把数组划分成了一段段的递增序列,在序列的最开始买入,最后卖出。举个例子:[2,1,25,4,5,6,7,2,4,5,1,5]。数组被划分成了5个递增序列,在第一个序列利润为0,第二个序列利润为24,第三个为3,第四个为3,第五个为4.总的利润是34。代码如下:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         int min = 0;
 4         int sump = 0;
 5         int mp = 0;
 6 
 7         for (int i = 1; i < prices.length; i++) {
 8             if (prices[i] < prices[i-1]){
 9                 sump = sump + mp;
10                 min = i;
11                 mp = 0;
12             }
13             else
14                 mp = prices[i] - prices[min];
15         }
16 
17         return sump + mp;
18     }
19 }

 

LeetCode OJ 122. Best Time to Buy and Sell Stock II

标签:

原文地址:http://www.cnblogs.com/liujinhong/p/5514239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!