简繁EN

LeetCodeNo. 004

[LeetCode with Python] 121. Best Time to Buy and Sell Stock

Contents

Problem

Problem page: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Topics: Array Dynamic Programming
Difficulty: Medium

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.


Analysis

Since we're only allowed one transaction, one pass through the array is enough to find the largest difference. But the maximum has to come to the right of the minimum. We can't just find the maximum and minimum and subtract the two, since that might give us the "maximum loss". The right way is to go through the array once, keeping track of the smallest value seen so far. At each element, subtract that minimum from the current value and keep track of the largest difference so far.
The original problem calls this dynamic programming. Maybe this is what's called one-dimensional dynamic programming? I've never quite got the hang of the definition of dynamic programming... Maybe I can think of it this way: if I can break a problem down and solve it step by step by building on solutions to subproblems, a bit like mathematical induction, then it's dynamic programming. The number of dimensions in the dynamic programming problem is the number of dimensions along which I can break it into subproblems. Here I can break it down by day, so it's one-dimensional dynamic programming. In the 0/1 knapsack problem, I can break it down along two dimensions, knapsack capacity and items, so it's two-dimensional dynamic programming.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
if None == prices or len(prices) < 2:
return 0
min = prices[0]
max_diff = 0
for i in range(1, len(prices)):
if prices[i - 1] < min:
min = prices[i - 1]
cur_diff = prices[i] - min
if cur_diff > max_diff:
max_diff = cur_diff
return max_diff

Article link: https://xnerv.wang/en/leetcode-best-time-to-buy-and-sell-stock/