A - 平坦な区間の判定 / Determining Flat Intervals Editorial by admin
gpt-5.3-codexOverview
This is a problem of determining “whether there exists a contiguous segment of length \(K\) where all heights are the same.”
By scanning the array once from left to right and counting how many consecutive elements have the same value, we can make this determination.
Analysis
A flat segment means that \(K\) consecutive elements are all the same.
In other words, this is equivalent to asking “is there a part where the same height appears \(K\) or more times consecutively?”
For example,
if \(H = [3,3,3,2,2,5]\) and \(K=3\), the leading 3,3,3 satisfies the condition, so the answer is Yes.
Naive Approach
One could check, for each starting position \(l\), whether the segment of length \(K\) from \(H_l\) to \(H_{l+K-1}\) consists entirely of the same value.
In this case, there are about \(N\) segments, and checking each segment takes up to \(K\) operations, resulting in \(O(NK)\) time complexity.
For \(N=2\times10^5\), this is likely too slow.
Improved Approach
We can simply scan the array from left to right while maintaining the “current run length.”
- If the current value is the same as the previous one, increment the run length
runby \(1\) - If it’s different, reset
run=1 - If at any point
run >= K, immediately outputYes
This completes in a single pass.
Algorithm
- Read \(N, K\) and the array \(H\).
- If \(K=1\), any single-element segment is flat, so immediately output
Yes. - Start with
run=1. - For \(i=1\) to \(N-1\), examine each element in order:
- If \(H_i = H_{i-1}\), then
run += 1 - Otherwise,
run = 1 - If
run >= K, outputYesand terminate
- If \(H_i = H_{i-1}\), then
- If no such segment is found after scanning the entire array, output
No.
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(N)\) (since the array \(H\) is stored in the implementation)
Implementation Notes
Since
K==1always results inYes, handling it first makes the logic clearer.The initial value of the run length
runshould be 1 (even a single element counts as 1 consecutive occurrence of the same value).Returning early as soon as the condition is met avoids unnecessary scanning.
Source Code
import sys
def main():
input = sys.stdin.readline
N, K = map(int, input().split())
H = [int(input()) for _ in range(N)]
if K == 1:
print("Yes")
return
run = 1
for i in range(1, N):
if H[i] == H[i - 1]:
run += 1
if run >= K:
print("Yes")
return
else:
run = 1
print("No")
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.3-codex.
posted:
last update: