'Rainwater harvesting problem for a series of walls and facing an issue on some large test cases of wrong answer 130/150 passed
I'm getting a wrong answer on finding the output for a huge input test case. I have thought the logic I have used to be appropriate. Please let me know what is the issue in this code ?
Some input examples to understand the logic are
- Input
N = 4
arr[] = {7,4,0,9}
- Output
10
Explanation:
Water trapped by above block of height 4 is 3 units and above block of height 0 is 7 units. So, the total unit of water trapped is 10 units.Input
N = 3
arr[] = {6,9,9}
- Output
0
- Explanation:
No water will be trapped.
long long trappingWater(int arr[], int n) {
// code here
vector<pair<int, int>> v;
long long count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != 0)
v.push_back({arr[i], i});
}
int z = v.size();
for (int i = z - 1; i >= 1; i--) {
int end_index = v[i].second;
int end_wall = v[i].first;
int maxer = 0;
for (int j = i - 1; j >= 0; j--) {
int start_index = v[j].second;
int start_wall = v[j].first;
long long temp = 0;
if (end_index - start_index >= 2)
temp =
(end_index - start_index - 1) * (min(end_wall, start_wall) - maxer);
if (temp > 0)
count += temp;
maxer = max(start_wall, maxer);
if (start_wall >= end_wall)
break;
}
// cout<<count<<endl;
}
return count;
}
this is the question link run/submit with this one https://practice.geeksforgeeks.org/problems/trapping-rain-water-1587115621/1#
Solution 1:[1]
found the solution it was basically a integer overflow but instead of crashing or giving an error it gave a garbage value , so it ran now
the solution is to change the value of temp to temp=1LL*(end_index - start_index -1 )1LL( min(end_wall,start_wall)-maxer );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Partha Pratim Ghose |
