zoukankan      html  css  js  c++  java
  • 122. Best Time to Buy and Sell Stock II--easy

    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 (i.e., buy one and sell one share of the stock multiple times).

    Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

    Example 1:

    Input: [7,1,5,3,6,4]
    Output: 7
    Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
    Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
    Example 2:

    Input: [1,2,3,4,5]
    Output: 4
    Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
    Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
    engaging multiple transactions at the same time. You must sell before buying again.
    Example 3:

    Input: [7,6,4,3,1]
    Output: 0
    Explanation: In this case, no transaction is done, i.e. max profit = 0.

    1.思考

    • 这个虽然是I的加强版,但是修改了条件之后解题思路就完全不一样了;
    • 通过将prices用折线图画出来,可以想到本题的解题思路是这样的:
      (1) 先将所有上升的价格进行标注;
      (2) 再将所有的上升价格起始、中止以及差值都记录下来;
      (3) 然后对每一段相邻的上升区间进行比较,若有重叠,则分段买入和抛售,对差值直接相加;若没有重叠,则在前一段初值买入,后一段中止值抛售,两者相减。
    • 这个方法的空间复杂度是较高的,还有待优化。

    2.实现
    Runtime: 8ms (99.42%)
    Memory: 9.8MB (5.39%)

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int len = prices.size();
            vector<int> fup(len, -1);
            
            for(int i=0; i<len-1; i++){
                if(prices[i]<prices[i+1])
                    fup[i] = 1;//The price will increase.
            }
            
            vector<vector<int>> incr;
            int j=0, f, b;
            while(j<len-1){
                if(fup[j]==1){
                    f = prices[j];
                    while(fup[j]==1)
                        j++;
                    b = prices[j];
                    incr.push_back(vector<int> {f, b, b-f});
                }
                j++;
            }
            
            int li = incr.size();
            if(li==0)
                return 0;
            if(li==1)
                return incr[0][2];
            
            int pro = incr[0][2];
            for(int i=0; i<li-1; i++){
                auto pi = incr[i];
                auto pj = incr[i+1];
                if(pi[1]>=pj[0])
                    pro += pj[2];
                else
                    pro += pj[1] - pi[0] - pi[2];
            }
            
            return pro;
        }
    };
    
  • 相关阅读:
    阅读笔记06
    阅读笔记05
    学习进度03
    四则运算03
    阅读笔记04
    求最大子数组值(有环版)
    合作项目02
    新的小组信息以及项目名称与介绍
    第六周进度条
    软件工程个人作业4(课堂练习&&课堂作业)
  • 原文地址:https://www.cnblogs.com/xuyy-isee/p/10601106.html
Copyright © 2011-2022 走看看