1299. 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.

 

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
class Solution {
    public int[] replaceElements(int[] arr) {
        int n = arr.length;
        int m = arr[n - 1];
        int[] res = new int[n];
        
        for(int i = n - 1; i >= 1; i--){
            m = Math.max(arr[i], m);
            res[i - 1] = m;
        }
        res[n - 1] = -1;
        return res;
    }
}

从右到左记录每一个max

上一篇:【leetcode】1299. Replace Elements with Greatest Element on Right Side


下一篇:R语言统计入门第二章R语言环境——2.2作图系统