Similar Problems

Similar Problems not available

Maximum And Sum Of Array - Leetcode Solution

Companies:

LeetCode:  Maximum And Sum Of Array Leetcode Solution

Difficulty: Hard

Topics: dynamic-programming bit-manipulation array  

Problem: Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. Return true if there is a 132 pattern in nums, otherwise, return false.

Example 1: Input: nums = [1,2,3,4] Output: false Explanation: There is no 132 pattern in the sequence.

Example 2: Input: nums = [3,1,4,2] Output: true Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3: Input: nums = [-1,3,2,0] Output: true Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0], and [-1, 2, 0].

Solution: To solve the problem we can use a stack. We will iterate through the array and keep adding elements to the stack. Whenever we find an element that is smaller than the top element of the stack, we know we have found the '2' of the '132' pattern. We will then keep popping elements from the stack until we find an element that is greater than the current element, which will be the '1' of the '132' pattern. If we find such an element, we return true, otherwise we continue iterating through the array.

To keep track of potential '3's, we will keep an integer variable called 'max' which represents the maximum element we have seen so far. Whenever we pop an element from the stack, we update 'max' if the popped element is greater than 'max'. This way, we know that any element we find after popping from the stack can be a potential '3'.

Code:

public boolean find132pattern(int[] nums) { Stack<Integer> stack = new Stack<Integer>(); int max = Integer.MIN_VALUE; for (int i = nums.length - 1; i >= 0; i--) { if (nums[i] < max) { return true; } while (!stack.isEmpty() && nums[i] > stack.peek()) { max = stack.pop(); } stack.push(nums[i]); } return false; }

Time Complexity: O(n) Space Complexity: O(n)

Explanation: In the code, we first create a stack and initialize 'max' to the minimum integer value. We then iterate through the array in reverse order using a for loop. In each iteration, we first check if the current element is less than 'max'. If it is, we have found a '132' pattern and we return true. If not, we continue to the next step.

In the next step, we keep popping elements from the stack until we find an element that is greater than the current element, which will be the '1' of the '132' pattern. We update 'max' to the popped element if it is greater than the current 'max'. We then push the current element onto the stack.

If we have gone through the entire array and have not found a '132' pattern, we return false.

Overall, the time complexity is O(n) and the space complexity is also O(n) due to the use of a stack.

Maximum And Sum Of Array Solution Code

1