Zerojudge h081. 程式交易

Python 解答

n, d  = map(int, input().split()) #平行對應
stock = list(map(int, input().split()))

profit = 0        #紀錄獲利
buy    = stock[0] #紀錄目前持有的價錢
sold   = 0        #紀錄賣掉的價格
flag   = 1        #flag=1 (買入), flag=0(已賣出)

for i in range(1, n):
    if flag==1 and stock[i]-buy>=d:
        profit += (stock[i]-buy) #獲利結算
        sold   = stock[i]       #紀錄賣出價錢,才計算之後的買入
        flag   = 0              #紀錄狀態
    
    elif flag==0 and stock[i]<=sold-d:
        buy  = stock[i]
        flag = 1 
        
print(profit)