LeetCode-122:Best Time to Buy and Sell Stock II (多次股票交易最大利润)

来源:互联网 发布:大数据技术体系图 编辑:程序博客网 时间:2024/05/20 10:13

Question

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

Idea

有一个数组,其中的元素是第i个元素是第i天股票的价格.

寻找在该数组给出的天数中的最大利润,可以进行多次购售。但是必须完成一次购售交易后才可进行下一次交易。

  1. 首先不同于Question 121:Best Time to Buy and Sell Stock,这次可以进行多次购售股票,可以进行多次交易,所以解题思路则可能会完全不同。

  2. idea1:可以按照“121”的思路,但是需要在每次的购售之间加入入口标志和出口标志,最后返回几次购售最大值的总和。

    • 算法较为复杂,易错,不是一个好的解决思路。
  3. idea2:可以换一种思路,可以当天售出拥有的股票,然后再当天买入,以这种思想替代不卖出的举动。

    • 只要后面的价格可以盈利,也就是相邻两天,后者大于前者,则当天进行两种操作,前一天买入,后一天卖出;
    • 如果相邻的两天不能盈利,则不进行买卖。
    • 对所有的元素进行两两依次遍历,保存所有盈利的和,进而简化了问题。

Code

idea1—Java

public class Solution {    public int maxProfit(int[] prices) {        if (prices == null || prices.length == 0)            return 0;        int max = 0;        int total = 0;        int buy = prices[0];        boolean flag = true;        for (int i=1; i<prices.length; ++i){            if (flag == true && prices[i] < buy){                buy = prices[i];            }else if (flag == false && prices[i] < prices[i-1]){                flag = true;                buy = prices[i];                total = total + max;                max = 0;            }else{                flag = false;                int profit = prices[i]-buy;                if (max < profit)                    max = profit;            }        }        if (max == 0)            return total;        else            return total + max;    }}
  • 需要设置一个flag来判断买入和卖出的条件;
  • 注意当盈利为零的情况需要返回的值,以及正常非零的情况下需要返回的值;
  • 在完成依次交易后,需要将flag置true,max置0。
  • Runtime:2ms,beats:11.98%.

idea2—Java

public class Solution {    public int maxProfit(int[] prices) {        if (prices.length == 0)            return 0;        int profit=0;        for (int i=0; i<prices.length-1; i++){            if (prices[i+1]-prices[i] > 0){                profit = profit + prices[i+1]-prices[i];            }        }        return profit;    }}
  • idea2明显要简单很多,易理解,易处理。
  • Runtime:2ms,和idea1相同。
  • 时间复杂度都是O(n)
阅读全文
0 0