LeetCode Best Time to Buy and Sell Stock

BabbleDay posted @ 2015年7月17日 15:14 in 刷题防身 with tags python leetcode , 862 阅读

系列一

def maxProfit(self, prices):
        rtn = 0
        if len(prices)!=0:
            buy = prices[0]
            for i in range( len(prices) ):
                buy = min(buy, prices[i])
                rtn = max(rtn, prices[i]-buy)
        return rtn

系列二:正常考虑单调

def maxProfit(self, prices):
        buy, sell, rtn = -1, -1, 0
        for i in range(len(prices)-1):
            if buy==-1 and prices[i+1]>prices[i]:
                buy = prices[i]
            if buy!=-1 and prices[i+1]<prices[i]:
                sell = prices[i]
                rtn += sell - buy
                buy = -1
        if buy!=-1:
            rtn += prices[-1] - buy
        return rtn

而实际上。。。若今天比昨天高,那就昨买今卖就好了= =

def maxProfit(self, prices):
        rtn = 0
        for i in range(1,len(prices)):
            if prices[i]>prices[i-1]:
               rtn += prices[i] - prices[i-1]
        return rtn
Avatar_small
RBSE Model Paper Cla 说:
2022年8月20日 23:57

Rajasthan Board Model Paper 2023 Class 5 Pdf Download with Answers for Rajasthani Medium, English Medium, Hindi Medium, Urdu Medium & Students for Small Answers, Long Answer, Very Long Answer Questions, and Essay Type Questions to Term1 & Term2 Exams at official website. RBSE Model Paper Class 5 New Exam Scheme or Question Pattern for Sammittive Assignment Exams (SA1 & SA2): Very Long Answer (VLA), Long Answer (LA), Small Answer (SA), Very Small Answer (VSA), Single Answer, Multiple Choice and etc.

Avatar_small
HBSE Question Paper 说:
2022年9月02日 19:09

Haryana Board Model Paper 2023 Pdf Download for Bhiwani Board (BSEH/HBSE) Sample Question Bank or Question Paper Design for Class 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 (Matric/Secondary), Higher Secondary (Class 11 & 12 Grade) Question Paper for Hindi Medium, English Medium, Urdu Medium and others for Theory, Objective (MCQ) and Bit Questions. HBSE Question Paper New Exam Scheme or Question Pattern for Sammittive Assignment Exams (SA1 & SA2): Very Long Answer (VLA), Long Answer (LA), Small Answer (SA), Very Small Answer (VSA), Single Answer, Multiple Choice and etc.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter