my two solutions in python ways with simply explanation


  • 0
    F

    1 Solution 1

    # code block
    def maxProfit(prices):
    	dif=[0]
    	index=[]
    	profit=0
    	flag=0   #in
    	if len(prices)<2:
    		return 0
    	for i in range(len(prices)-1):
    		dif.append(prices[i+1]-prices[i])
    	if prices[1]>prices[0]:
    		index.append(prices[0])
    		flag=1 #out
    	for i in range(1,len(dif)-1):
    		if flag==0:
    			if dif[i]<=0:
    				if dif[i+1]>0:
    					index.append(prices[i])
    					flag=1
    		elif flag==1:
    			if dif[i]>=0:
    				if dif[i+1]<0:
    					index.append(prices[i])
    					flag=0
    	if prices[-1]>=prices[-2]:
    		index.append(prices[-1])
    	for i in range(len(index)):
    		for j in range(i+1,len(index),2):
    			if index[j]-index[i]>profit:
    				profit=index[j]-index[i]
    
    	return profit
    
    1. Solution 2
    # code block
    def maxProfit(prices):
    
    	while True:
    		try:
    
    			if prices[0]>=prices[1]:
    				prices.pop()
    			else:
    				break
    		except:
    			pass
    	while True:
    		try:
    
    			if prices[-1]<=prices[-2]:
    				prices.pop()
    			else:
    				break
    		except:
    			pass
    	
    	profit=0
    	for i in range(len(prices)):
    		for j in range(i+1,len(prices)):
    			if prices[j]-prices[i]>profit:
    				profit=prices[j]-prices[i]
    	
    	return profit
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.