def tj1(wall):
i=wall.index(min(wall))
sL=tj1(wall[:i]) if i>0 else 0
sR=tj1(wall[i+1:]) if i<len(wall)-1 else 0
return max(wall[i]*len(wall),sL,sR)
思路二(伸展版)
python复制代码
def tj2(wall):
sL=[]
for i in range(len(wall)):
s=1; h=wall[i]
for j in range(i,0,-1):
if(h>wall[j-1]):
s+=i-j; break
else:
s+=i-1
for j in range(i,len(wall)-1):
if(h>wall[j+1]):
s+=j-i; break
else:
s+=len(wall)-1-i
sL.append(s*h)
return max(sL)
(增加一个用while代替for...else的版本)
python复制代码
def tj2w(wall): # while版
sMax=0; N=len(wall)
for i in range(N):
w=1; h=wall[i]
j=i
while(j>0 and h<=wall[j-1]): j-=1
w+=i-j
j=i
while(j<N-1 and h<=wall[j+1]): j+=1
w+=j-i
sNew=w*h
if(sNew>sMax): sMax=sNew
return sMax
测试代码
python复制代码
def timeit(num=100):
t1=[];t2=[];size=[]
for i in range(num):
K=random.choices(range(1,1000001),k=random.randint(1,10000)); N=len(K)
size.append(N)
t0=time.time()
ans=tj2(K)
t2.append(time.time()-t0)
t0=time.time()
ans=tj1(K)
t1.append(time.time()-t0)
return t1,t2,size