Sunday, February 23, 2020

1299. Replace Elements with Greatest Element on Right Side (easy)

Q:
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
A:

class Solution {
public:
    vector<int> replaceElements(vector<int>& arr) {
        // search from right and record the so far greatet
        // declaring new vector and copying element of old vector, constructgor method, deep copy
        vector<int> res(arr); 
        int n = arr.size();
        int sofar = -1, tmp=0;
        for(int j = n-1;j>=0; --j)
        {
            tmp = max(sofar, res[j]);
            res[j] = sofar;
            sofar = tmp;
        }
        return res;
    }
};


1 comment:

  1. You should see how my pal Wesley Virgin's autobiography begins in this shocking and controversial video.

    You see, Wesley was in the army-and soon after leaving-he discovered hidden, "SELF MIND CONTROL" tactics that the government and others used to obtain anything they want.

    These are the same methods lots of celebrities (notably those who "come out of nothing") and the greatest business people used to become rich and successful.

    You probably know how you utilize only 10% of your brain.

    Really, that's because the majority of your BRAINPOWER is UNCONSCIOUS.

    Perhaps that conversation has even taken place IN YOUR very own head... as it did in my good friend Wesley Virgin's head around 7 years back, while driving an unregistered, trash bucket of a car without a driver's license and with $3.20 in his bank account.

    "I'm very fed up with living paycheck to paycheck! When will I become successful?"

    You've taken part in those types of questions, am I right?

    Your success story is waiting to be written. All you need is to believe in YOURSELF.

    UNLOCK YOUR SECRET BRAINPOWER

    ReplyDelete