"""
題目分析:
這題是中等題,本來想的是用遍歷,但是看到數字範轉10^6;看了題解,實際這個是最長上升子序列;這題按score或age都可行
理論:dp
1.先按score進行排序,將組score和age組合新數組data
data[i][0]記錄score
data[i][1]記錄age
2.循環data的下標idx和數據score,age;並初始化dp[idx]=score
3.循環0~idx的數據
4.如果滿足約束條件age[i]<age
5.當前dp[idx]=max(dp[idx],dp[j]+score)
6.返回max(dp)
注意/難點:
需要先進行排序,以確保重複項不會缺失
"""
import numpy as np
class Solution:
def bestTeamScore(self, scores: list, ages: list) -> int:
data=list(zip(scores,ages)) #將組score和age組合新數組data
data.sort(key=lambda x:(x[0],x[1])) #按scores,age排序
print(np.array(data))
dp=[0]*len(scores) #生成dp
#循環data的下標idx和數據score,age
for idx, (score,age) in enumerate(data):
dp[idx]=score #初始化dp的值
for i in range(0,idx): #循環0~idx的數據
if data[i][1]<=age: #滿足約束條件
dp[idx]=max(dp[idx],dp[i]+score)
print(idx,dp)
return max(dp) #返回值
scores = [1,3,5,10,15]
ages = [1,2,3,4,5]
# scores=[1,1,1,1,1,1,1,1,1,1]
# ages=[811,364,124,873,790,656,581,446,885,134]
ans=Solution().bestTeamScore(scores,ages)
print(ans)
最後輸結果:
data
每次dp的變化