Java 10 lines and C++ 12 lines linear time complexity O(n) with explanation
The approach is same as Next Greater Element I\nSee explanation in my solution to the previous problem\nThe only difference here is that we use stack to keep th
The approach is same as *Next Greater Element I*\nSee explanation in [my solution to the previous problem](https://discuss.leetcode.com/topic/77916/java-10-lines-linear-time-complexity-o-n-with-explanation)\nThe only difference here is that we use ```stack``` to keep the **indexes** of the **decreasing** subsequence\n\n**Java**\n```\n    public int[] nextGreaterElements(int[] nums) {\n        int n = nums.length, next[] = new int[n];\n        Arrays.fill(next, -1);\n        Stack<Integer> stack = new Stack<>(); // index stack\n        for (int i = 0; i < n * 2; i++) {\n            int num = nums[i % n]; \n            while (!stack.isEmpty() && nums[stack.peek()] < num)\n                next[stack.pop()] = num;\n            if (i < n) stack.push(i);\n        }   \n        return next;\n    }\n```\n**C++**\n```\n    vector<int> nextGreaterElements(vector<int>& nums) {\n        int n = nums.size();\n        vector<int> next(n, -1);\n        stack<int> s; // index stack\n        for (int i = 0; i < n * 2; i++) {\n            int num = nums[i % n]; \n            while (!s.empty() && nums[s.top()] < num) {\n                next[s.top()] = num;\n                s.pop();\n            }\n            if (i < n) s.push(i);\n        }   \n        return next;\n    }\n```
[]