-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinMaxAverage.java
More file actions
43 lines (35 loc) · 898 Bytes
/
Copy pathMinMaxAverage.java
File metadata and controls
43 lines (35 loc) · 898 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Question:
Given an integer array nums, find the smallest and largest
elements in the array and return their average.
The average is calculated as:
(smallest + largest) / 2.0
Example:
Input: nums = [1, 3, 5, 7]
Output: 4.0
Explanation:
Smallest = 1
Largest = 7
Average = (1 + 7) / 2.0 = 4.0
*/
class Solution {
public double minimumAverage(int[] nums) {
// Assume first element is both smallest and largest
int smallest = nums[0];
int largest = nums[0];
// Find the smallest element
for (int num : nums) {
if (num < smallest) {
smallest = num;
}
}
// Find the largest element
for (int num : nums) {
if (num > largest) {
largest = num;
}
}
// Return the average as a double
return (smallest + largest) / 2.0;
}
}