zoukankan      html  css  js  c++  java
  • 122. Best Time to Buy and Sell Stock II (Array;Greedy)

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

    法I:从左向右扫描,找到每个递增序列的第一个元素和最后一个元素

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            if(prices.empty()) return 0;
            if(prices.size() == 1) return 0;
            int maxProfit = 0;
            int buyPrice = 0;
            int prePrice;
            bool asc = false; //if in ascending sequence
            
            vector<int>::iterator it= prices.begin(); 
            prePrice = *it;
            it++;
            for(; it < prices.end(); it++)
            {
                if ((*it)>prePrice)
                {
                    if(!asc) //find the first element in the ascending sequence
                    {
                        buyPrice = prePrice;
                        asc = true;
                    }
                }
                else  if ((*it)< prePrice)
                {
                    if(asc) //find the last element in the ascending sequence
                    {
                        maxProfit = prePrice - buyPrice + maxProfit;
                        asc = false;
                    }
                }
                prePrice = *it;
            }
            if(asc)
            {
                maxProfit = prePrice - buyPrice + maxProfit;
            }
            return maxProfit;
        }
    };

     法II:递增就就算profit

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int profit = 0;
            for (int i=0; i<(int)prices.size()-1; i++) {
                if (prices[i+1] > prices[i])
                    profit += prices[i+1] - prices[i];
            }
            return profit;
        }
    };
  • 相关阅读:
    Spark-sql windows 下 执行错误.
    notepad ++ 注册表
    log4j 配置文件 示例
    linux 查看 进程 内存占用
    spring boot 常见错误解决
    python 轻量 web 框架 Bottle 使用
    Spring cloud eureka 添加 spring-security
    vue can‘ not resolver sass-loader 的 解决办法。
    外国人眼中的珍珠奶茶是啥?
    75.2亿美元:诺基亚、微软终于在一起
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4878340.html
Copyright © 2011-2022 走看看