Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Feature #2: Path Cost

Sumit Rawal answered on May 24, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers


Feature #2: Path Cost

0

We need to calculate the amount of water that has accumulated above each road elevation and sum it up. At a single index/elevation (X), the amount of water depends on the heights of the highest bars to it left and right, regardless of how far apart they are. Upon further exploration, we also observe that the elevation (X) + the height of the water above this elevation, is equivalent to the minimum height of the highest bars around it. Therefore, the accumulation of the water, above a certain point (X), can be calculated using the formula:

Water = minimum ( left_max, right_max ) - value_X

Here, left_max is the highest bar to the left of a certain point (X) and right_max is the highest bar to the right of point (X). If there is no highest bar on either side, the elevation at (X) will be considered the highest bar.

To see this in practice, refer to the diagram below. Here, the left_max (

3

3

units) is smaller than the right_max (

4

4

units). Therefore, the minimum(right_max, left_max) is the left_max (

3

3

units). The elevation at X itself is

2

2

units. Hence, the water above X is

3

2

=

1

3−2=1

unit​.

X

X

Here is how implementation will take place:

Traverse through the array once.

Calculate the left_max for each point and save it in an array.

Traverse the array again to do the same with right_max.

Traverse the array once more, and use this data to find the amount of water above each point using the formula mentioned above.

Let’s look at the code for the solution: 

Popularity 1/10 Helpfulness 1/10 Language scala
Source: Grepper
Tags: path scala
Link to this answer
Share Copy Link
Contributed on May 24 2023
Sumit Rawal
0 Answers  Avg Quality 2/10


X

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
X
Grepper Account Login Required

Oops, You will need to install Grepper and log-in to perform this action.