Link Search Menu Expand Document

1299. Replace Elements with Greatest Element on Right Side

Solution Code

C#

public class Solution {
    public int[] ReplaceElements(int[] arr) {
        int size = arr.Length, maxVal = -1;
        int[] answer = new int[size];
        
        for (int i = size - 1; i >= 0; i--) {
            answer[i] = maxVal;
            maxVal = Math.Max(maxVal, arr[i]);
        }
        
        return answer; 
    }
}

C++

class Solution {
public:
    vector<int> replaceElements(vector<int>& arr) {
        int size = arr.size(), maxVal = -1;
        vector<int> answer (size, 0);
        
        for (int i = size - 1; i >= 0; i--) {
            answer[i] = maxVal;
            maxVal = max(maxVal, arr[i]);
        }
        
        return answer;
    }
};

Java

class Solution {
    public int[] replaceElements(int[] arr) {
        int size = arr.length, maxVal = -1;
        int[] answer = new int[size];
        
        for (int i = size - 1; i >= 0; i--) {
            answer[i] = maxVal;
            maxVal = Math.max(maxVal, arr[i]);
        }
        
        return answer;
    }
}

© 2023. All rights reserved.