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

Posted Black_Knight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 122. 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).

【思路】

相比较上一个题目,这个题目对交易放松了限制,可以做多笔交易,但是在进行下一笔交易之前必须先完成上一笔交易,而且相同交易只能做一次。我的思路是:如果价格在未来上涨,那么我就在当前买入。如果价格在未来下跌,我就在当前卖出。这样的结果就是把数组划分成了一段段的递增序列,在序列的最开始买入,最后卖出。举个例子:[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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode122-Best Time to Buy and Sell Stock II

leetcode-122. Best Time to Buy and Sell Stock II

Java [Leetcode 122]Best Time to Buy and Sell Stock II

LeetCode 122. Best Time to Buy and Sell Stock II

122. Best Time to Buy and Sell Stock leetcode解题笔记

[LeetCode]题解(python):122-Best Time to Buy and Sell Stock II