[LeetCode]#1299. Replace Elements with Greatest Element on Right Side
1 min readApr 18, 2020
Environment: Python 3.7
Key technique: append
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.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Constraints:
1 <= arr.length <= 10^4
1 <= arr[i] <= 10^5
Analysis:
As below, find right side maximum number and add it to ans list. We can get answer when the searching list is finish.
Solution:
class Solution:
def replaceElements(self, arr):
l=len(arr)
ans=[]
for i in range(l-1):
arr_r=max(arr[i+1:])
ans.append(arr_r)
ans.append(-1)
return ans
Submitted result: