We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
longlongintsolve(vector<int>arr){intn=arr.size();intM[n];longlongintsum=0;M[0]=-1;//Create an Array M where M[i] is the index of the closest element to the left of arr[i] that is greater than or equal to arr[i]. If there is no such element let M[i]=-1for(inti=1;i<n;i++){if(arr[i-1]>=arr[i])M[i]=i-1;else{intj=i-1;while(j>0&&arr[j]<arr[i]&&M[j]!=-1)j=M[j];M[i]=j;}}set<int>covered;for(inti=n-1;i>0;i--){//If a particular series of elements have been covered make sure we don't cover the index i againif(covered.find(i)!=covered.end())continue;intj=i;longk=1;//Find the number of elements (k) where height is same and in between all elements are of lesser heightwhile(j>0&&arr[M[j]]==arr[j]){k++;covered.insert(j);j=M[j];}//Add the number of ways of making pairs from k elements multiplied by 2 (bidirectional) to the overall sumsum=sum+(k*(k-1));}returnsum;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Jim and the Skyscrapers
You are viewing a single comment's thread. Return to all comments →
Here is my code with comments: