Open In App

Python program to find the Strongest Neighbour

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Read the input array i.e,arr1.
  2. 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.
  3. print the values of arr2.

Below is the implementation.

Python3




# define a function for finding
# the maximum for adjacent
# pairs in the array
def maximumAdjacent(arr1, n):
   
      # array to store the max
    # value between adjacent pairs
    arr2 = [] 
     
    # iterate from 1 to n - 1
    for i in range(1, n):
       
        # find max value between
        # adjacent  pairs gets
        # stored in r
        r = max(arr1[i], arr1[i-1])
         
        # add element
        arr2.append(r)
         
    # printing the elements
    for ele in arr2 :
        print(ele,end=" ")
 
if __name__ == "__main__" :
   
  # size of the input array
  n = 6 
   
  # input array
  arr1 = [1,2,2,3,4,5]
   
  # function calling
  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
Previous
Next
Share your thoughts in the comments

Similar Reads