Longest alternating-sign run MEDIUM Secvente (BAC) 25 XP 0 solved
Mobile coding works. A laptop is faster for long sessions.

Problem

Read a positive natural number `n` followed by `n` integers forming a sequence `v[1], v[2], ..., v[n]`. A contiguous subarray `v[i], v[i+1], ..., v[j]` has alternating signs if, traversed from left to right, the elements alternate between positive and negative: positive, negative, positive, negative, ... or the reverse. Determine the length of the longest such subarray and print its elements. If the value `0` appears in the sequence, it breaks any alternating-sign run (a zero element is neither positive nor negative). If there are several subarrays of maximum length, choose the first one.

Input format

Input input.txt

The first line contains `n`. The second line contains `n` integers separated by spaces. - `1 <= n <= 1000` - `-1000 <= v[i] <= 1000` - a single nonzero element forms an alternating-sign run of length `1`

Output format

Output output.txt

The first line contains a single natural number: the length of the longest alternating-sign run. The second line contains the elements of that run, separated by spaces.

Example

input
8

3 -1 4 -2 5 5 -6 7
output
5

3 -1 4 -2 5

Ready to solve this challenge?

Create a free account to write code, submit solutions, and track your progress.

⌨️ Keyboard Shortcuts

Code Editor
Run Code
Ctrl Enter
Submit Code
Ctrl Shift Enter
Format Code
Shift Alt F
Toggle Comment
Ctrl /
Undo
Ctrl Z
Redo
Ctrl Y
Navigation
Global Search
/
Show Shortcuts
?
Close Modal
Esc

🔍 Interactive Debugger

0 / 0

Analyzing your code...

📦 Variables

No variables yet

📚 Call Stack
main() line 1
📤 Output
We use cookies

Essential cookies are always active. You can choose to enable preference and analytics cookies. Learn more