东方财富20190806后台开发笔试(交错字符串,买卖股票)

东方财富2:买卖股票的最佳时机


原题解(python3)——leetcode:买卖股票的最佳时机(买卖一次)

延伸——leetcode:买卖股票的最佳时机(不限次数)


这题与原题略有不同,笔试题是可以买卖两次(原题是买卖一次),因此我想到的思路是可以将数组拆分,用左数组的最大收益加上右边数组的最大收益,代码如下:

# 找一次买卖时的最大值
def helper(prices): 
    r, m = 0, float('inf')  # r代表收益, m代表最小值
    for p in prices:
        r, m = max(r, p - m), min(m, p)
    return r

prices = [7, 1, 5, 3, 6, 4]
n = len(prices)
max_ = 0
for i in range(n):
    max_ = max(helper(prices[0:i]) + helper(prices[i:]), max_)

print(max_)
posted @ 2019-08-07 09:55  pandaWaKaKa  阅读(871)  评论(0编辑  收藏  举报