calculateSpan(price, n) { var ans=[]; var stack=[]; for(var i=0;i<n;i++) { if(stack.length==0) ans.push(-1); else if(stack.length>0 && stack[stack.length-1][0]>price[i]) { ans.push(stack[stack.length-1][1]) } else if(stack.length>0 && stack[stack.length-1][0]<=price[i]) { while(stack.length>0 && stack[stack.length-1][0]<=price[i]) { stack.pop() } if(stack.length==0) ans.push(-1); else { ans.push(stack[stack.length-1][1]) } } stack.push([price[i],i]); } for(var i=0;i<n;i++) { ans[i]=i-ans[i] } return ans; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter