Guest User

Untitled

a guest
May 27th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. Given n non-negative integers representing an elevation map where the width of each bar is 1,
  2. compute how much water it is able to
  3. trap after raining.
  4.  
  5. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case,
  6. 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
  7.  
  8. Example:
  9.  
  10. Input: [0,1,0,2,1,0,1,3,2,1,2,1]
  11. Output: 6
  12.  
  13. keywords:
  14. integer array, arr[i] >= 0 for any i, representing width of each bar = 1, height[i] = arr[i]
  15. ask: how much water it is able to trap after raining
  16.  
  17.  
  18.  
  19. ---
  20. --- ---
  21. --- --- ---
  22.  
  23. brute force solution ->left = 1, right = 2, itself = 0, naive store min(left, right) - arr[i] -> O(n)
  24. time complexity: O(n^2) - brute force - efficient
  25. [2, 1, 0, 1, 3]
  26. -> 3
  27. [0, 1, 2, 1, 0]
  28. ->
  29. [4, 1, 0, 1, 3]
  30. ->
  31. [0, 3, 4, 3, 1]
  32. -> left to right
  33. -> right to left
  34. -> get minimum for two iteration, find the sum O(n)
  35. descending stack: [2, 1, 0,] -> maximum height = 2
  36. ascending stack: [0, 1, 3] -> maximum height = 3
  37.  
  38. -> left to right linear time complexity ->
  39. [3, 4, 5] -> descending order
  40. [5, 6, 7]
  41. range from index = 3 to 7, height -> water height = min(2, 3) = 2
  42.  
  43.  
  44.  
  45.  
  46. public int trap(int[] height) {
  47. if(height == null)
  48. return 0;
  49.  
  50. var length = height.Length();
  51.  
  52.  
  53. // two iterations - left to right
  54. //[2, 1, 0, 1, 3]
  55. //-> 3
  56. //[0, 1, 2, 1, 0]
  57.  
  58. var leftToRight = ScanFromLeftToRight(height);
  59. var rightToLeft = ScanFromLeftToRight(Array.Reverse(height)); // <- [1, 2, 3] -> [3, 2, 1] -> left to right
  60. rightToLeft = Array.Reverse(rightToLeft);
  61.  
  62.  
  63. // get the minimum of both
  64. for()
  65.  
  66. // get the sum of two array
  67. }
  68.  
  69. private static int[] ScanFromLeftToRight(int[] height)
  70. {
  71. var leftToRight = new int[length];
  72. var max = height[0];
  73. for(int index = 0; index < length; index++)
  74. {
  75. var current = leftToRight[index];
  76. if(current > max)
  77. {
  78. max = current;
  79. leftToRight[index] = 0;
  80. }
  81. else
  82. {
  83. leftToRight[index] = max - current;
  84. }
  85. }
  86.  
  87. return leftToRight;
  88. }
Add Comment
Please, Sign In to add comment