Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
brute force
暴力搜索,没什么好说的
当前位置 $i$ ,搜索其后所有的可能答案,取最大的
1 2 3 4 5 6 7 8 9 10 11 12 13 14
defbrute_force(arr, start): if start >= len(arr): return0 max_profit = 0 for i inrange(start, len(arr)): tmp_max_profit = 0 for j inrange(start+1, len(arr)): if arr[j] > arr[i]: profit = brute_force(arr, j+1) + arr[j] - arr[i] if profit > tmp_max_profit: tmp_max_profit = profit if tmp_max_profit>max_profit: max_profit = tmp_max_profit return max_profit