Codeforces Round 450 (Div. 2) C. Remove Extra One

Remove Extra One

time limit per test: 2 second
memory limit per test: 256 megabytes
input: standard input
output: standard output

You are given a permutation p p p of length n n n. Remove one element from permutation to make the number of records the maximum possible.

We remind that in a sequence of numbers a 1 , a 2 , … , a k a_1,a_2,\dots,a_k a1,a2,,ak the element a i a_i ai is a record if for every integer j j j ( 1   ≤   j   <   i 1 \leq j < i 1 j<i) the following holds: a j   <   a i a_j < a_i aj<ai.

Input

The first line contains the only integer n n n ( 1   ≤   n   ≤   1 0 5 1 \leq n \leq 10^5 1 n 105) — the length of the permutation.

The second line contains n n n integers p 1 ,   p 2 ,   … ,   p n p_1, p_2, \dots, p_n p1,p2,,pn ( 1   ≤   p i   ≤   n 1 \leq p_i \leq n 1 pin) — the permutation. All the integers are distinct.

Output

Print the only integer — the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one.

Example

i n p u t \tt input input
1
1
o u t p u t \tt output output
1
i n p u t \tt input input
5
5 1 2 3 4
o u t p u t \tt output output
5

Note

In the first example the only element can be removed.

Tutorial

不妨转换一下题意:删除一个元素后,有多少位置的数值等于前缀最大值

所以可以对每一个位置进行计数,对于删去 x x x 后,需要记录

  • 哪些位置在删去 x x x 后变成了前缀最大值,即该值前面只有 x x x 这个数比该位置的数大
  • 哪些位置在删去 x x x 后不再是前缀最大值,即删除前 x x x 就是前缀最大值

根据上面两种情况,我们可以计算每个元素删去时,满足条件的位置数值会发生怎样的变化,最后取最大值即可

此解法时间复杂度为 O ( n ) \mathcal O(n) O(n)

Solution

#include <bits/stdc++.h>
using namespace std;

signed main() {
    int n, ans = 0;
    cin >> n;
    vector<int> p(n), mx(2, -1), mid(n);
    for (int i = 0; i < n; ++i) {
        cin >> p[i];
        if (mx[0] == -1 or p[i] > p[mx[0]]) { // 是否为最大值
            mid[i]--;
            mx[1] = mx[0];
            mx[0] = i;
        } else if (mx[1] == -1 or p[i] > p[mx[1]]) { // 是否仅小于最大值
            mid[mx[0]]++;
            mx[1] = i;
        }
    }
    for (int i = 0; i < n; ++i) {
        if (mid[i] > mid[ans] or (mid[i] == mid[ans] and p[i] < p[ans])) {
            ans = i;
        }
    }
    cout << p[ans] << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值