let arr = [] let m = 0 height.forEach((v,index)=>{ let n = 1 if(m <= v) { m = 0 } while(v>height[index+n] && height.slice(index+1).findIndex((k)=>{return k>height[index+n]})!==-1 && n+index<height.length && v>=m) { if(height.slice(index+1).findIndex((k)=>{return k>=v})!==-1) { arr.push(v-height[index+n]) m = v } else { let max = 0 max = height.slice(index+1).sort((a,b)=>{ return b-a })[0] arr.push(max-height[index+n]) m = max } n = n+1 } })