@tony3 I would like to tell you some of my understanding.

First, you must notice that buy[0] = -prices[0], that means you buy the stock at the 0th price.

Second, buy[i] means on the ith day, the amount of cash when you hold the stock, and sell[i] means on the ith day, the amount of cash when you don't hold the stock.

So, just focus on ith day. buy[i] = max(buy[i-1], sell[i-1])-prices[i], the first term means you don't buy at ith price, the second term means you buy at ith price use cash on (i-1)th day. sell[i] = max(sell[i-1], max[i-1]+prices[i]-fee), the first term means you just hold cash of (i-1)th day, the second term means you sell the stock at the price on ith day so you need to add prices[i] on yesterday's holding stock cash which is buy[i-1].

Because we want maximum sell[N-1], so we need to max sell[N-2] and buy[N-2], so iterate util 0. But when we are coding, we code from 0 to N-1.

Subcategories

LeetCode Weekly Contest 55