您的位置:首页 > 编程语言 > Python开发

【LeetCode with Python】 Best Time to Buy and Sell Stock II

2008-12-07 13:33 585 查看
博客域名:http://www.xnerv.wang

原题页面:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

题目类型:数组,贪婪法

难度评价:★★

本文地址:/article/1377538.html

Say you have an array for which the ith element is the price of a given stock on dayi.

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:

    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        len_prices = len(prices)
        if len_prices <= 1:
            return 0

        start = prices[0]
        index = 1
        income = 0
        total_income = 0
        while index < len_prices:
            cur = prices[index]
            if cur >= prices[index - 1]:
                income = cur - start
                index += 1
                if len_prices == index:
                    total_income += income
            else:
                total_income += income
                income = 0
                start = cur
                index += 1

        return total_income
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: