In this task, I worked on finding the minimum and maximum values from an array. Instead of writing everything in one place, I used a function to make the code cleaner and reusable.
What I Did
I created a function called find_min_max that takes an array as input and returns both the smallest and largest values.
For example:
Input: [1, 4, 3, 5, 8, 6]
Output: [1, 8]
How I Solved It
First, I assumed that the first element of the array is both the minimum and maximum. Then I used a loop to go through each number in the array.
While looping:
If a number is smaller than the current minimum, I update the minimum
If a number is larger than the current maximum, I update the maximum
At the end, I return both values as a list.
CODE:
'''python class Solution:
def getMinMax(self, arr):
minimum = arr[0]
maximum = arr[0]
for num in arr[1:]:
if num < minimum:
minimum = num
elif num > maximum:
maximum = num
return [minimum, maximum]'''
How It Works
The function checks each element only once. It keeps updating two variables (minimum and maximum) as it goes through the array. This makes the solution efficient and easy to understand.
United States
NORTH AMERICA
Related News
CBS News Shutters Radio Service After Nearly a Century
5h ago
White House Unveils National AI Policy Framework To Limit State Power
5h ago
Officer Leaks Location of French Aircraft Carrier With Strava Run
5h ago
Microsoft Says It Is Fixing Windows 11
5h ago
NASA's Hubble Unexpectedly Catches Comet Breaking Up
5h ago