Problem
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Algorithm
If price[i-m] < price[i] < price[i+n], then price[i+n] - price[i] + price[i] - price[i-m] = price[i+n] - price[i-m]. So use the closest one to calculate is ok. Add all the closest inreamental is the answer.
Code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
prices_len = len(prices)
max_p = prices[prices_len-1]
index = prices_len-2
ans = 0
while index >= 0:
if max_p > prices[index]:
ans = ans + max_p - prices[index]
max_p = prices[index]
else:
max_p = prices[index]
index -= 1
return ans