Problem ยท Array

Sum of Subarray Regions

Learn this problem
โ— MediumPatreonINTERNOA

Problem statement

There is a straight line of students of various heights. The students' heights are given in the form of an array, in the order they are standing in the line.

Consider the region of a student as the length of the largest subarray that includes that student's position, and in which that student's height is equal to maximum height among all students present in that subarray. Return the sum of the region of all students.

Function

sumOfSubarrayRegions(heights: int[]) โ†’ int

Complete the function sumOfSubarrayRegions in the editor.

sumOfSubarrayRegions has the following parameter:

  1. int[] heights: an array of integers representing the heights of students

Returns

int: the sum of the lengths of all regions of all students

Examples

Example 1

heights = [3, 5, 6]return = 6

For example-

  • The longest subarray in which the first student's height is equal to the maximum height among all other students is [3]; thus, the length of the region of the first student is 1.
  • The longest subarray in which the second student's height is equal to maximum height among all other students is [3, 5]; thus, the length of the region of the second student is 2.
  • The longest subarray in which the third student's height is equal to the maximum height among all other students is [3, 5, 6]; thus, the length of the region of the third student is 3.
  • Thus, the sum of the lengths of all regions of all students is 1 + 2 + 3 = 6.

Constraints

๐ŸŠ๐ŸŠ

More Patreon problems

drafts saved locally
public int sumOfSubarrayRegions(int[] heights) {
  // write your code here
}
heights[3, 5, 6]
expected6
checking account