• leetcode Best Time to Buy and Sell Stock II


    和上一题类似Best Time to Buy and Sell Stock,这里还是用一个数组存每天股票价格,你有很多次买入卖出的机会,但是每次买入要在前一次卖出前。

    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,2,3,2,5,6,那么第一次在1买入,因为2比1大,然后我们看3,比2大,所以可以到3再卖出因为和你1买入2卖出再买入2再卖出3的收益是一样的。所以2被跳过,但是现在到3之后的2了,3到2会损失,那是我们不能允许的。所以3就要卖出。然后当前就从3之后的2开始考虑,继续如上考虑,最后就可以获得做大收益。

    class Solution {
    public:
        int maxProfit(vector<int> &prices) 
        {
            int len = prices.size();
            int profit = 0, i = 0, maxInd = 0, curp = 0;
            while(i < len - 1)
            {
                if (prices[i] >= prices[i+1])
                {
                    i++;
                    continue;
                }
                maxInd = i + 1;
                curp = prices[i];
                while(i + 1 < len && prices[i] <= prices[i+1])
                {
                    maxInd = i+1;
                    i++;
                }
                profit += prices[maxInd] - curp;
                i = maxInd + 1;
            }
            return profit;
        }
    };
  • 相关阅读:
    Memcached安装
    BarCode条形码生成库
    WebAPI示例
    JDK安装目录分析-两个jre和三个lib
    JDK安装与环境变量配置
    【Selenium专题】高亮显示页面元素
    cannot be resolved to a type (Java)
    Java中获取运行代码的类名、方法名
    【Selenium专题】 FAQ_对象识别_Compound class names are not supported
    Html5新标签解释及用法
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4138597.html
Copyright © 2020-2023  润新知