zoukankan      html  css  js  c++  java
  • 【LeetCode】122. Best Time to Buy and Sell Stock II

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

    核心思想:每一段单调递增区间的收益累加。

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int m = prices.size();
            if(m == 0)
                return 0;
                
            int ret = 0;
            int buy = prices[0];
            int last = prices[0];
            for(int i = 1; i < m; i ++)
            {
                if(prices[i] < last)
                {
                    ret += (last - buy);
                    buy = prices[i];
                }
                last = prices[i];
            }
            ret += (last - buy);
            return ret;
        }
    };

  • 相关阅读:
    树状数组
    LCA最近公共祖先
    ordered_set
    马拉车算法
    数论
    图论
    其他
    线段树
    序列自动机
    优先队列
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3764255.html
Copyright © 2011-2022 走看看