|
U
Pro22. Single Pass Min and Max with Comparisons
Easy
Problem Description
Find the minimum and maximum element in an array of N integers in one traversal. Compare elements in pairs so that total comparisons between array elements is at most ⌈3N/2⌉.
Input Format
- •Line 1: An integer N (1≤N≤105).
- •Line 2: N space-separated integers A1,A2,…,AN.
Output Format
- •Line 1: Two space-separated integers:
min_val max_val - •Line 2: An integer representing total element comparisons performed.
Example 1:
Input:
5 3 1 9 7 2
Output:
1 9 6
Explanation: Pairs evaluated in 6 comparisons <= ceil(3*5/2)=8.
Example 2:
Input:
1 100
Output:
100 100 0
Explanation: Single element requires 0 comparisons.
Example 3:
Input:
2 5 8
Output:
5 8 1
Explanation: Comparing 5 and 8 takes 1 comparison.
Constraints:
Standard integer bounds: 32-bit signed integer or input range [1, 10^5].Time complexity target: O(N) or O(N log N) where applicable.Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online
Code
|Loading Code Editor...
SavedLn 1, Col 1
param_1 =
param_2 =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit