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
  • 相关阅读:
    音乐
    脚本注释的作用
    JavaScript状态栏冒泡
    JavaScript动态显示时间
    正则表达式
    JavaScript数组的最大长度
    加密(编码)web.config中的信息(如:连接字符串)
    JavaScript实现EMAIL功能
    JavaScript检测分辨率
    JavaScript如何给网页滚动条加上颜色?
  • 原文地址:https://www.cnblogs.com/yancea/p/7510278.html
Copyright © 2011-2022 走看看