题意:Say you have an array for which the ith element is the price of a given stock on day i.
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.
思路:题目还是挺有意思的,很有生活气息啊~等于是要求数组的最大差值,开始的时候又做错了。。直接用时间复杂度O(n^2)的方法做的,直接报 Time Limit Exceeded,所以这题的目的还是要用O(n)的方法来解,下面这种做法挺有意思的,在递进的顺序中找出数组的最小数,和它子数组中的最大值的差就是结果:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
min_num, max_so_far = float('inf'), 0
for i in prices:
min_num = min(i, min_num)
max_so_far = max(i-min_num, max_so_far)
return max_so_far
后来看到discuss里有个人提到这题就是求子数组最大和的问题,有个很有名的解法叫做Kadane’s algorithm(卡登算法)卡登算法讲解。这哥们把这个数组[7, 1, 5, 3, 6, 4]转化成该项和前一项的差,即[0,-6,4,-2,3,-2]。仔细观察不难发现,转化后的数组中子数组的和就是对应子数组首尾项的差,比如4+(-2)+(3)=5-1+3-5+6-3=6-1=5,所以就转化成了求子数组最大和的问题了:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_cur, max_so_far = 0, 0
for i in xrange(1,len(prices)):
max_cur = max(0, max_cur + prices[i]-prices[i-1])
max_so_far = max(max_cur, max_so_far)
return max_so_far