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.

Find the array the array.

Example 1:

Input: arr = {17,18,5,4,6,1}
Output: arr={18,6,6,6,1,-1}

Approach

Java

import java.util.Arrays;

public class RepElemGreatRightSide {
    public static void main(String[] args) {
        int[] arr = { 17185461 };
        int res[] = replaceElements(arr);
        System.out.println(Arrays.toString(res));
    }

    static int[] replaceElements(int[] arr) {
        int n = arr.length;
        if (n == 0)
            return arr;
        int max1 = arr[n - 1];
        arr[n - 1] = -1;
        for (int i = n - 2; i >= 0; i--) {
            int x = arr[i];
            arr[i] = max1;
            max1 = Math.max(max1, x);
        }
        return arr;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

vector<intreplaceElements(vector<int>& arr
{
    int n=arr.size();
    if(n==0)
       return arr;
    int max1=arr[n-1];
    arr[n-1]=-1;
    for(int i=n-2;i>=0;i--)
      {
          int x=arr[i];
          arr[i]=max1;
          max1=max(max1,x);
      }
        return arr;
}
int main()
{
   vector<intarr ={17,18,5,4,6,1};
   arr=replaceElements(arr);
   for(int i=0;i<arr.size();i++)
      cout<<arr[i]<<" ";
   return 0;
}


No comments:

Post a Comment