LeetCode 1063. Number of Valid Subarrays Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1063. Number of Valid Subarrays

Description

Given an integer array nums, return the number of non-empty subarrays with the leftmost element of the subarray not larger than other elements in the subarray.

A subarray is a contiguous part of an array.

 

Example 1:

Input: nums = [1,4,2,5,3]
Output: 11
Explanation: There are 11 valid subarrays: [1],[4],[2],[5],[3],[1,4],[2,5],[1,4,2],[2,5,3],[1,4,2,5],[1,4,2,5,3].

Example 2:

Input: nums = [3,2,1]
Output: 3
Explanation: The 3 valid subarrays are: [3],[2],[1].

Example 3:

Input: nums = [2,2,2]
Output: 6
Explanation: There are 6 valid subarrays: [2],[2],[2],[2,2],[2,2],[2,2,2].

 

Constraints:

  • 1 <= nums.length <= 5 * 104
  • 0 <= nums[i] <= 105

Solutions

Solution 1

PythonJavaC++GoTypeScript
class Solution: def validSubarrays(self, nums: List[int]) -> int: n = len(nums) right = [n] * n stk = [] for i in range(n - 1, -1, -1): while stk and nums[stk[-1]] >= nums[i]: stk.pop() if stk: right[i] = stk[-1] stk.append(i) return sum(j - i for i, j in enumerate(right))(code-box)

Solution 2

PythonJavaC++GoTypeScript
class Solution: def validSubarrays(self, nums: List[int]) -> int: n = len(nums) stk = [] ans = 0 for i in range(n - 1, -1, -1): while stk and nums[stk[-1]] >= nums[i]: stk.pop() ans += (stk[-1] if stk else n) - i stk.append(i) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !