Amazon | OA | USA
Anonymous User
5089

image
Solution(All cases passed)
``
function countDecreasingRatings(ratings) {
// Write your code here

let n = ratings.length;    
if(n ==0) return 0;    
let i =0;    
let result =1;    

for(let j =1; j < n; j++){
    
    if((ratings[j-1] - ratings[j]) == 1){
        result +=(j-i+1);
    }else{
        i =j;
        result +=1;
    }
    
}
return result;

}

``

image

Solution(All cases passed)

``
function getTotalImbalance(weight) {
// Write your code here

let mod = Math.pow(10,9)+7;
let arr = weight;

let PLE = new Array(arr.length).fill(-1);
let NLE = new Array(arr.length).fill(arr.length);

let PBE = new Array(arr.length).fill(-1);
let NBE = new Array(arr.length).fill(arr.length);

findPreviousLess(PLE, arr);
findNextLess(NLE, arr);

findPreviousBig(PBE, arr);
findNextBig(NBE, arr);

let minsum =0;
let maxsum =0;

for(let i=0; i<arr.length;i++){
minsum += (((i-PLE[i])(NLE[i]-i)) arr[i]);
}

for(let i=0; i<arr.length;i++){
maxsum += (((i-PBE[i])*(NBE[i]-i)) * arr[i]);
}

return (maxsum - minsum);




function findPreviousLess(PLE, arr){
let stack = [];
for(let i=0; i<arr.length;i++){
while(stack.length >0 && arr[stack[stack.length-1]] >=arr[i]){
stack.pop();
}

if(stack.length > 0){
PLE[i] = stack[stack.length -1];
}

stack.push(i);
}       
}

function findNextLess(NLE, arr){
let stack = [];
for(let i=arr.length-1; i>=0;i--){
while(stack.length >0 && arr[stack[stack.length-1]] >arr[i]){
stack.pop();
}

if(stack.length > 0){
NLE[i] = stack[stack.length -1];
}

stack.push(i);
}       
}

function findPreviousBig(PBE, arr){
let stack = [];
for(let i=0; i<arr.length;i++){
while(stack.length >0 && arr[stack[stack.length-1]] <=arr[i]){
stack.pop();
}

if(stack.length > 0){
PBE[i] = stack[stack.length -1];
}

stack.push(i);
}       
}

function findNextBig(NBE, arr){
let stack = [];
for(let i=arr.length-1; i>=0;i--){
while(stack.length >0 && arr[stack[stack.length-1]] < arr[i]){
stack.pop();
}

if(stack.length > 0){
NBE[i] = stack[stack.length -1];
}

stack.push(i);
}       
}
}

``

Comments (6)