Python Programming: How to Find the Maximum Number in an Array

Python Programming: How to Find the Maximum Number in an Array

In this blog we are going to find the Maximum value in array in python with and without inbuilt function.Here we are going to see 3 Methods to achieve it

1. Without Using inbuilt Function

a = [1,5,12,8,3]
temp =-1 #temporary Variable

for i in range(len(a)):
if(a[i]>temp):
temp=a[i]
print(temp)

The time complexity of the given code is O(n), where n is the length of the array 'a'. This is because the code iterates through the array once using a for loop, and the time taken for each iteration is constant.

The space complexity of the given code is O(1), as it uses a single variable 'max_num' to store the maximum number found so far, and the size of this variable does not depend on the size of the input array.

In summary, the given code has a time complexity of O(n) and a space complexity of O(1). It is an efficient way to find the maximum number in an array in Python.

2.Using Inbuilt Function

a = [1,5,12,8,3]
print(max(a))

The time complexity of the max(a) function call in Python, where a is a list of length n, is O(n). This is because the max() function iterates through the list once to find the maximum element.

The space complexity of this code is O(1), as it does not require any additional memory allocation or data structures beyond the input list a. The max() function uses a constant amount of memory to keep track of the current maximum value while iterating through the list.

3.Using InBuilt Function

a = [1,5,12,8,3]
a.sort(reverse=True)
print(a[0])

The time complexity of the given code is O(n log n), where n is the length of the input array 'a'. This is because the sort() function in Python uses a comparison-based sorting algorithm (typically Timsort) that has an average time complexity of O(n log n).

The space complexity of the code is O(1), as it doesn't require any additional memory space other than the input array 'a'. The sort() function performs an in-place sort on the input array, so it doesn't require any additional space for temporary arrays or data structures.