Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

42. trapping-rain-water.cpp #471

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

PurvalBhude
Copy link

Putting code in C++ for problem 42.trapping-rain-water problem

  1. For every element we can precalculate and store the highest bar on the left and on the right (say stored in arrays left[] and right[]).
  2. Then iterate the array and use the precalculated values to find the amount of water stored in this index,
    which is the same as ( min(left[i], right[i]) – arr[i] )

Follow the steps mentioned below to implement the approach:

  1. Create two arrays left[] and right[] of size N. Create a variable (say max) to store the maximum found till a certain index during traversal.
  2. Run one loop from start to end:
  3. In each iteration update max and also assign left[i] = max.
  4. Run another loop from end to start:
  5. In each iteration update max found till now and also assign right[i] = max.
  6. Traverse the array from start to end.
  7. The amount of water that will be stored in this column is min(left[i], right[i]) – array[i]
  8. Add this value to the total amount of water stored
  9. Print the total amount of water stored.

test cases :
// test case 1
// height = [0,1,0,2,1,0,1,3,2,1,2,1]
// output = 6

// test case 2
// height = [4,2,0,3,2,5]
// output = 9

Complexity Analysis:

Time Complexity: O(N). Only one traversal of the array is needed, So time Complexity is O(N).
Space Complexity: O(N). Two extra arrays are needed, each of size N.

Putting code in C++ for problem 42.trapping-rain-water problem
Copy link

welcome bot commented Dec 21, 2023

I can tell this is your first pull request! Thank you I'm so honored. 🎉🎉🎉 I'll take a look at it ASAP!

@PurvalBhude
Copy link
Author

PurvalBhude commented Apr 17, 2024

@anandfresh please suggest me changes in this pull request .

@PurvalBhude
Copy link
Author

now i updated the file. now it will pass the checks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants