PowerShell Script to Find Largest Number in Array
Use
$array | Measure-Object -Maximum to find the largest number in an array, for example: ($array | Measure-Object -Maximum).Maximum returns the largest value.Examples
Input[3, 5, 1, 9, 2]
Output9
Input[10, 10, 10]
Output10
Input[-5, -1, -10]
Output-1
How to Think About It
To find the largest number in an array, look at each number and keep track of the biggest one you have seen so far. At the end, the biggest number you kept is the largest in the array.
Algorithm
1
Get the array of numbers.2
Start with the first number as the largest.3
Compare each number in the array to the current largest.4
If a number is bigger, update the largest number.5
After checking all numbers, return the largest number.Code
powershell
$array = @(3, 5, 1, 9, 2) $largest = ($array | Measure-Object -Maximum).Maximum Write-Output "Largest number is $largest"
Output
Largest number is 9
Dry Run
Let's trace the array [3, 5, 1, 9, 2] through the code
1
Input array
The array is 3, 5, 1, 9, 2
2
Measure-Object finds maximum
It compares all numbers and finds 9 as the largest
3
Output result
Prints 'Largest number is 9'
| Number | Current Largest |
|---|---|
| 3 | 3 |
| 5 | 5 |
| 1 | 5 |
| 9 | 9 |
| 2 | 9 |
Why This Works
Step 1: Using Measure-Object
The Measure-Object -Maximum command scans the array and finds the highest number.
Step 2: Extracting the Maximum
The property .Maximum holds the largest value found by Measure-Object.
Step 3: Output the result
We use Write-Output to print the largest number in a readable format.
Alternative Approaches
Using a loop to find largest
powershell
$array = @(3, 5, 1, 9, 2) $largest = $array[0] foreach ($num in $array) { if ($num -gt $largest) { $largest = $num } } Write-Output "Largest number is $largest"
This method manually compares each number and is easy to understand but longer than Measure-Object.
Using Sort-Object
powershell
$array = @(3, 5, 1, 9, 2) $largest = $array | Sort-Object -Descending | Select-Object -First 1 Write-Output "Largest number is $largest"
Sorting the array and picking the first element works but is less efficient for large arrays.
Complexity: O(n) time, O(1) space
Time Complexity
The script checks each element once, so time grows linearly with array size.
Space Complexity
No extra space is needed besides a few variables, so space is constant.
Which Approach is Fastest?
Using Measure-Object is efficient and concise; manual loops are clear but longer; sorting is slower due to extra operations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Measure-Object -Maximum | O(n) | O(1) | Quick and clean for any array size |
| Manual loop | O(n) | O(1) | Clear logic for beginners |
| Sort-Object then select | O(n log n) | O(n) | When sorted array is also needed |
Use
Measure-Object -Maximum for a quick and clean way to find the largest number.Forgetting to extract the
.Maximum property and printing the whole Measure-Object result.