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
  • 相关阅读:
    redis使用基础(一) ——Redis基本概述与安装配置
    Linux学习闲谈(三) ——SVN用法及切版本与合版本
    Linux学习闲谈(二) ——SVN版本控制拾遗
    Linux学习闲谈(一)——Shell基本操作与命令
    linux1
    git命令
    ubuntu
    laradock
    实用工具
    grumphp在docker里问题
  • 原文地址:https://www.cnblogs.com/yancea/p/7510278.html
Copyright © 2011-2022 走看看