题解 | #合唱队#

合唱队

https://www.nowcoder.com/practice/6d9d69e3898f45169a441632b325c7b4

# 读取input
n = int(input())
heights = list(map(int, input().split()))

# 计算从左开始最长的增长序列
def longest_increasing_subsequence(heights):
    lis = [1] * len(heights)
    for i in range(1, len(heights)):
        for j in range(i):
            if heights[i] > heights[j]:
                lis[i] = max(lis[i], lis[j] + 1)
    return lis

# 计算最长的从右开始的降低序列
def longest_decreasing_subsequence(heights):
    lds = [1] * len(heights)
    for i in range(len(heights) - 2, -1, -1):
        for j in range(i + 1, len(heights)):
            if heights[i] > heights[j]:
                lds[i] = max(lds[i], lds[j] + 1)
    return lds

# 计算lis 和 lds array
lis = longest_increasing_subsequence(heights)
lds = longest_decreasing_subsequence(heights)

# 聚合lis和lds去寻找最长的合唱队队形
max_choir_length = 0
for i in range(n):
    # 计算在i集中的合唱队队形长度
    choir_length = lis[i] + lds[i] - 1
    max_choir_length = max(max_choir_length, choir_length)

# 计算最少去掉多少学生
min_students_to_remove = n - max_choir_length

print(min_students_to_remove)

全部评论

相关推荐

hso_:哈哈哈哈哈哈我没offer一样在同一道题开喷了
投递深圳同为数码等公司10个岗位
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务