- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathNextGreaterElement.cs
47 lines (42 loc) · 1.94 KB
/
NextGreaterElement.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
usingSystem;
usingSystem.Collections.Generic;
namespaceAlgorithms.Stack
{
/// <summary>
/// For each element in an array, the utility finds the next greater element on the right side using a stack.
/// @author Mohit Singh. <a href="https://github.com/mohit-gogitter">mohit-gogitter</a>
/// </summary>
publicclassNextGreaterElement
{
/// <summary>
/// Finds the next greater element for each element in the input array.
/// The next greater element for an element x is the first element greater than x to its right.
/// If there is no greater element, -1 is returned for that element.
/// </summary>
/// <param name="nums">The array of integers to find the next greater elements for.</param>
/// <returns>An array where each index contains the next greater element of the corresponding element in the input array, or -1 if no such element exists.</returns>
/// <exception cref="ArgumentNullException">Thrown when the input array is null.</exception>
publicint[]FindNextGreaterElement(int[]nums)
{
int[]result=newint[nums.Length];
Stack<int>stack=newStack<int>();
// Initialize all elements in the result array to -1
for(inti=0;i<nums.Length;i++)
{
result[i]=-1;
}
for(inti=0;i<nums.Length;i++)
{
// While the stack is not empty and the current element is greater than the element
// corresponding to the index stored at the top of the stack
while(stack.Count>0&&nums[i]>nums[stack.Peek()])
{
intindex=stack.Pop();
result[index]=nums[i];// Set the next greater element
}
stack.Push(i);// Push current index to stack
}
returnresult;
}
}
}