202109-2非零段划分

题目描述

A1,A2,⋯,An 是一个由 n 个自然数(非负整数)组成的数组。我们称其中 Ai,⋯,Aj 是一个非零段,当且仅当以下条件同时满足:

  • 1≤i≤j≤n;
  • 对于任意的整数 k,若 i≤k≤j,则 Ak>0;
  • i=1 或 Ai−1=0;
  • j=n 或 Aj+1=0。

下面展示了几个简单的例子:

  • A=[3,1,2,0,0,2,0,4,5,0,2] 中的 4 个非零段依次为 [3,1,2]、[2]、[4,5] 和 [2];
  • A=[2,3,1,4,5] 仅有 1 个非零段;
  • A=[0,0,0] 则不含非零段(即非零段个数为 0)。

现在我们可以对数组 A 进行如下操作:任选一个正整数 p,然后将 A 中所有小于 p 的数都变为 0。试选取一个合适的 p,使得数组 A 中的非零段个数达到最大。若输入的 A 所含非零段数已达最大值,可取 p=1,即不对 A 做任何修改。

输入格式

从标准输入读入数据。

输入的第一行包含一个正整数 n。

输入的第二行包含 n 个用空格分隔的自然数 A1,A2,⋯,An。

输出格式

输出到标准输出。

仅输出一个整数,表示对数组 A 进行操作后,其非零段个数能达到的最大值。

'''水平面岛屿
找出数值中的最大值,作为最高的水平面,
不断下降水面,记录每次下降之后的岛屿的数量,进行比较选出最多的岛屿数量。'''
n = int(input())
nums = [0]+list(map(int,input().split()))+[0]
point = {}
max_ = 0
for id, value in enumerate(nums):#下标和值
    if not value:#值!=0
        continue
    max_ = max(max_, value)#找最大值
    if value not in point:#添加到字典中
        point[value] = [id]
    else:
        point[value].append(id)#值对应的下标
island = [0]*(n+2)#岛屿
temp = 0#非零段个数能达到的最大值
top = 0
for data in range(max_, 0, -1):#从最大值开始 下降
    if data not in point:
        continue
    #print('the height is ',data,point[data])
    for i in point[data]:#值为data时的 下标
        if island[i-1] == 0 and island[i+1] == 0:#岛屿露出水面
            top += 1
        elif island[i-1] == 1 and island[i+1] == 1:#是其他岛屿的一部分
            top -= 1        
        island[i] = 1
    temp = max(top,temp)
print(temp)

 

posted @ 2023-03-07 00:47  吃人不吐葡萄  阅读(43)  评论(0)    收藏  举报