import java.util.Stack; public class StockSpan { public static void stockSpan(int[] arr) { int[] span = new int[arr.length]; Stack<Integer> s = new Stack<>(); span[0] = 1; s.push(0); for(int i = 1; i < arr.length; i++) { while (!s.isEmpty() && arr[i] > arr[s.peek()]) s.pop(); if (s.isEmpty()) span[i] = i + 1; else span[i] = i - s.peek(); s.push(i); } for (int j : span) { System.out.println(j + " "); } return; } public static void main(String[] args){ int[] arr={100,80,60,70,60,85,100}; stockSpan(arr); } }
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