cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2024 · EasyRunning state

Longest Natural Run

National Olympiad — Regional round (2024 season)

Submission name: rise.cpp

Problem summary

Find the longest contiguous subsequence equal to 1,2,3,… . If there is no 1, its length is zero.

Input

N, followed by N positive integers.

Output

The maximum natural-run length.

Constraints

2 < N < 1000000; each value is less than 1000000.

Worked example

An independently prepared example for this explanation.

Input

8
5 1 2 7 1 2 3 6

Output

3

Solution analysis

  1. Keep the length of the natural run ending at the previous position. Because a valid run begins at 1 and increases by one, its last value always equals its length.
  2. A new 1 starts a run of length one. Otherwise, a value equal to currentLength+1 extends a nonempty run; every other value breaks it. Update the best length after each value.
  3. The sample contains runs 1,2 and 1,2,3. Their lengths are two and three. The larger increasing pieces beginning at 5 or 7 are irrelevant because natural runs must start with 1.

Why it works

At each position the update preserves exactly the length of the valid natural suffix: it either starts, extends, or ceases to exist. Every natural subsequence ends somewhere, so the maximum suffix length is the answer.

Complexity: O(N) time and O(1) extra space; numbers are processed as a stream.

Watch out. The subsequence is contiguous and must start at 1. A new 1 can restart a run immediately after a break.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    int current = 0, best = 0;
    for (int i = 0; i < n; i++) {
        int value;
        cin >> value;
        // A natural suffix ends with its own length.
        if (value == 1) {
            current = 1;
        } else if (current > 0 && value == current + 1) {
            current++;
        } else {
            current = 0;
        }
        best = max(best, current);
    }
    cout << best << '\n';
}

Source: Arena Olimpiici ↗