Find the next greater element for every element in an array?
int[] NextGreaterElements(int[] nums) {
int n = nums.Length;
int[] result = new int[n];
Stack<int> stack = new Stack<int>();
for (int i = n - 1; i >= 0; i--) {
while (stack.Count > 0 && stack.Peek() <= nums[i]) {
stack.Pop();
result[i] = stack.Count == 0 ? -1 : stack.Peek();
stack.Push(nums[i]);
return result;
Explanation:
Traverse from right to left, use stack to keep track of next greater elements in O(n).