Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Assistant
First, I need to understand what's being asked: Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment o
Key values given: 1, ,
Working through the calculation: Solution: Maximum Non-Decreasing Subsegment
Problem Understanding
We need to find the longest contiguous subarray where elements are in non-decreasing order (each element ≥ the previous element). Approach
We'll use a single-pass greedy algorithm:
Maintain two variables:
current_length: length of the current non-decreasing subsegment ending at position i
max_length: maximum length found so far
For each element, check if it extends the previous non-decreasing subsegment or starts a new one. Algorithm
code
Initialize: current_length = 1, max_length = 1
For i from 2 to n:
If a[i] >= a[i-1]:
current_length = current_length + 1 (extend current segment)
Else:
current_length = 1 (start new segment)
max_length = max(max_length, current_length)
Return max_length