[Leetcode] Replace Elements with Greatest Element on Right Side

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.After doing so, return the array.
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
class Solution(object):
def replaceElements(self, arr):
"""
:type arr: List[int]
:rtype: List[int]
"""

arr.reverse()
maximum_num = 0

for i in range(len(arr)):
if maximum_num < arr[i]:
maximum_num = arr[i]
if i == 0:
maximum_num = arr[i]
arr[i] = -1

arr[i] = maximum_num

for i in range(len(arr)-2, -1, -1):
arr[i + 1] = arr[i]
arr[0] = -1
arr.reverse()
return arr

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Matthew Boyd

Matthew Boyd

Learning, and posting my findings!