第一题:经典楼梯问题
第二题 拆迁问题,求最少分房数,规则:
相邻的家户人多的必须比人少的分的多。
每户至少分一房。
人数相同的家户分的房数可以不同。
def house( person ):
# write code here
if not person:
return 0
n=len(person)
if n==1:
return 1
if n==2:
return 2 if person[0]==person[1] else 3
dp=[0]*n#显然可以优化为O(1)
dp[0]=1
dp[1]=2 if person[0]==person[1] else 3
sx=0 if person[0]<=person[1] else 1 #sx是右边开始升序对的数目
r=1 if person[0]>=person[1] else 2 #r是最右边的分房数
for i in range(2,n):
if person[i]==person[i-1]:#如果和最右的相等,则直接加1
sx=0
dp[i]=dp[i-1]+1
r=1
elif person[i]>person[i-1]:#如果大于最右的,只需要r+1
sx=0
dp[i]=dp[i-1]+r+1
r+=1
else:
sx+=1
dp[i]=dp[i-1]+sx
return dp[-1]
print(house([4,1,3,3,3]))
这个dp的关键在于知道从右左的逆序对。
因为 34加一个2,这个3不受影响的。