Python program to find the Strongest Neighbour
Last Updated :
28 Feb, 2023
Given an array arr[] of N positive integers. The task is to find the maximum for every adjacent pair in the array.
Examples:
Input: 1 2 2 3 4 5
Output: 2 2 3 4 5
Input: 5 5
Output: 5
Approach:
- Read the input array i.e,arr1.
- for i=1 to sizeofarray-1
- find the max value between arr1[i] and arr1[i-1].
- store the above value in another array i.e, arr2.
- print the values of arr2.
Below is the implementation.
Python3
def maximumAdjacent(arr1, n):
arr2 = []
for i in range ( 1 , n):
r = max (arr1[i], arr1[i - 1 ])
arr2.append(r)
for ele in arr2 :
print (ele,end = " " )
if __name__ = = "__main__" :
n = 6
arr1 = [ 1 , 2 , 2 , 3 , 4 , 5 ]
maximumAdjacent(arr1, n)
|
Output:
2 2 3 4 5
Time complexity: O(n), where n is the size of the input array. This is because the program iterates through the array once to calculate the maximum value between adjacent pairs and then iterates through the array again to print the output.
Auxiliary space: O(n) because the program creates an additional array, arr2, to store the maximum value between adjacent pairs. The size of arr2 is equal to n-1 because the maximum value cannot be calculated for the last element in the array since it does not have an adjacent element.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...