公式

A - モニタリングの最高値 / Monitoring Peak 解説 by admin

gpt-6-astra-medium

Overview

We want to find the largest digit contained in the string \(S\). We check from \(9\) down to \(0\) and output the first digit found.

Analysis

The load level has only \(10\) possibilities, from \(0\) to \(9\). Therefore, we can find the maximum value by checking whether each digit is contained in \(S\), starting from the largest.

For example, when \(S =\) 30752, neither 9 nor 8 is contained, but 7 is. Since we have already confirmed that there are no larger digits, the answer is \(7\).

Note that for this problem, a naive approach of inspecting all characters one by one and updating the maximum value is also fast enough. No special optimizations are necessary. The provided code takes advantage of the small number of distinct digits and adopts the method of searching in descending order.

Algorithm

  1. Read \(N\) and the string \(S\).
  2. Check \(d\) in the order \(9, 8, \ldots, 0\).
  3. If the character corresponding to the digit \(d\) is contained in \(S\), output \(d\) and terminate.

The first \(d\) found is contained in \(S\), and no digits larger than \(d\) are contained. Therefore, \(d\) is the maximum load level.

In addition, since the length of \(S\) is at least \(1\) and consists only of digits, at least one digit is guaranteed to be found.

Complexity

  • Time Complexity: \(O(N)\)
    Each search in the string takes \(O(N)\) time, and we perform it at most \(10\) times. Since \(10\) is a constant, the overall time complexity is \(O(N)\).
  • Space Complexity: \(O(N)\)
    Required to store the input string \(S\). Other additional space is \(O(1)\).

Implementation Notes

  • The provided code is in C++. It converts the integer \(d\) to the corresponding digit character using char('0' + d). For example, if \(d = 7\), it becomes the character '7'.

  • s.find(...) returns the position if the specified character is found, and std::string::npos if it is not found.

  • Once a digit is found, we output it and terminate with return 0;. Because we are checking in descending order, there is no need to check any smaller digits.

  • By including 0 in the search targets, the code correctly handles the case where \(S\) consists entirely of 0s.

    Source Code

// 問題文から独立に実装: 9 から下へ、S に含まれる最初の数字を探す
#include <iostream>
#include <string>
int main() {
    int n; std::string s; std::cin >> n >> s;
    for (int d = 9; d >= 0; --d) {
        if (s.find(char('0' + d)) != std::string::npos) { std::cout << d << std::endl; return 0; }
    }
}

This editorial was generated by gpt-6-astra-medium.