leetcode之Best Time to Buy and Sell Stock问题

来源:互联网 发布:重装系统数据恢复 编辑:程序博客网 时间:2024/06/03 17:48

问题描述:

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

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

示例:

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.(个人认为这个示例帮助还是挺大的)

问题来源:Best Time to Buy and Sell Stock (具体地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/#/description)

思路:这道题和后面的几个题目非常的相似(Best Time to Buy and Sell Stock II,Best Time to Buy and Sell Stock III),可以看作是同一类问题(DP类问题),后面我也会做一个总结。这道题可以采用Maximum subarray problem(最大化子数组)来解决,有关该类问题的详细描述,这里有详细介绍(Maximum subarray problem),可以仔细阅读下。而解决该类问题,著名的Kadane's algorithm就可以登场了,该算法可以看作动态规划(dynamic programming.)的一种,甚至可以看作是动态规划(动态规划详细介绍)的一个简单例子,该算法的时间复杂度是线性的,即O(n)。该题的disscuss中最热门的代码,相当简练。但是很不好理解。本人在这也把它贴出来了,但是我把它拆成了更加容易的版本。

代码:

该段代码的注释比较啰嗦,但是希望能给一部人能够带来帮助吧。

disscuss中的热门回答:

代码非常简练,运行时间肯定比我的代码短一些,大家也不妨可以试着理解一下,其实也是采用Max Subarray的办法来解决的。




原创粉丝点击