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

    思路:贪心算法(Greedy Algorithm)
    1.为了获取最多的利润,应该在每一段价格上升的区间的开头买入,末尾卖出;
    2.在每一小段上升序列中最大差值累加得到结果;
    3.即在股票价格处于上升期的时候,在最低点买入,在最高点卖出;
    4.且每一小段的最大差值就是这段序列的最后一个点的价格减去这段序列第一个点的价格,与每一次从第一个点与第二点的差值一直累加所得结果相同:

       diff_prices = prices[i] - prices[i-1] ;

    class Solution():
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            max_profit = 0
            for i in range(1, len(prices)):
                diff_prices = prices[i] - prices[i-1]
                if diff_prices > 0:
                    max_profit += diff_prices
            return max_profit
  • 相关阅读:
    玩家移动
    人物上线(激活玩家之后)
    map 玩家上线
    无锁的环形队列
    随笔
    std::bind
    如何查找文件中的schema约束
    myeclipse便捷导包方式
    21 求1+2!+3!+...+20!的和
    20 求出这个数列的前 20 项之和
  • 原文地址:https://www.cnblogs.com/yancea/p/7510278.html
Copyright © 2011-2022 走看看