
Problem
Solution
Submissions
Maximum and Minimum in Array
Certification: Basic Level
Accuracy: 100%
Submissions: 1
Points: 5
Write a JavaScript program to find both the maximum and minimum values in an array of numbers. The function should return an object containing both values. Given an array of integers, efficiently determine the largest and smallest numbers without using built-in Math.max() or Math.min() functions.
Example 1
- Input: arr = [3, 1, 4, 1, 5, 9, 2, 6]
- Output: {max: 9, min: 1}
- Explanation:
- The array contains numbers: [3, 1, 4, 1, 5, 9, 2, 6].
- Starting with first element 3 as both max and min.
- Comparing each element: 1 is smaller than current min (3), so min becomes 1.
- Element 4 is between current min (1) and max (3), no change.
- Element 5 is greater than current max (4), so max becomes 5.
- Element 9 is greater than current max (5), so max becomes 9.
- Final result: maximum is 9, minimum is 1.
- The array contains numbers: [3, 1, 4, 1, 5, 9, 2, 6].
Example 2
- Input: arr = [10, -5, 0, 15, -10, 8]
- Output: {max: 15, min: -10}
- Explanation:
- The array contains numbers: [10, -5, 0, 15, -10, 8].
- Starting with first element 10 as both max and min.
- Element -5 is smaller than current min (10), so min becomes -5.
- Element 0 is between current min (-5) and max (10), no change.
- Element 15 is greater than current max (10), so max becomes 15.
- Element -10 is smaller than current min (-5), so min becomes -10.
- Element 8 is between current min (-10) and max (15), no change.
- Final result: maximum is 15, minimum is -10.
- The array contains numbers: [10, -5, 0, 15, -10, 8].
Constraints
- 1 ≤ arr.length ≤ 10^5
- -10^9 ≤ arr[i] ≤ 10^9
- Array contains at least one element
- Time Complexity: O(n) where n is the length of array
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Initialize both max and min variables with the first element of the array
- Start iterating from the second element (index 1) of the array
- For each element, compare it with the current maximum value
- If current element is greater than max, update the max value
- Similarly, compare current element with the current minimum value
- If current element is smaller than min, update the min value
- Return an object containing both max and min values