Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

nearest greater to right

int[] arr = { 2, 4, 6, 2, 5 };
var stack = new Stack<int>();
var list = new List<int>();
for (int i = arr.Length - 1; i >= 0; i--)
{
	while( stack.Count > 0 && stack.Peek() < arr[i])
    {
    	stack.Pop();
    }
    list.Add(stack.Count == 0 ? -1 : stack.Peek());
    stack.Push(arr[i]);
}
 
PREVIOUS NEXT
Tagged: #nearest #greater
ADD COMMENT
Topic
Name
8+6 =