Python Program to Find Maximum in Array
max(array) which returns the largest element in the list.Examples
How to Think About It
Algorithm
Code
def find_maximum(arr): max_value = arr[0] for num in arr: if num > max_value: max_value = num return max_value # Example usage array = [3, 5, 1, 2, 4] print(find_maximum(array))
Dry Run
Let's trace the array [3, 5, 1, 2, 4] through the code
Initialize max_value
max_value = 3 (first element)
Compare 3 with max_value
3 is not greater than 3, max_value stays 3
Compare 5 with max_value
5 is greater than 3, update max_value to 5
Compare 1 with max_value
1 is not greater than 5, max_value stays 5
Compare 2 with max_value
2 is not greater than 5, max_value stays 5
Compare 4 with max_value
4 is not greater than 5, max_value stays 5
Return max_value
Return 5 as the maximum
| Current Number | max_value |
|---|---|
| 3 | 3 |
| 5 | 5 |
| 1 | 5 |
| 2 | 5 |
| 4 | 5 |
Why This Works
Step 1: Start with first element
We assume the first element is the largest to have a starting point for comparison.
Step 2: Compare each element
We check each number with the current maximum using if num > max_value to find if there's a bigger number.
Step 3: Update maximum
If a bigger number is found, we update max_value to that number to keep track of the largest.
Step 4: Return result
After checking all numbers, the max_value holds the largest number in the array.
Alternative Approaches
array = [3, 5, 1, 2, 4] print(max(array))
array = [3, 5, 1, 2, 4] array.sort() print(array[-1])
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once, so it takes time proportional to the number of elements, which is O(n).
Space Complexity
The program uses only a few variables and does not create extra arrays, so space is O(1).
Which Approach is Fastest?
Using the built-in max() is fastest and simplest. Manual iteration is clear and efficient. Sorting is slower due to O(n log n) time.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual iteration | O(n) | O(1) | Learning and control over logic |
| Built-in max() | O(n) | O(1) | Quick and clean code |
| Sorting | O(n log n) | O(1) | When array needs sorting anyway |
max() function for a quick and clean solution.