Why is trapping rainwater problem giving runtime error?


  • 0
    S

    class Solution {
    public:
    int trap(vector<int>& a) {
    if(a.size()<=1 )
    return 0;
    int v[a.size()],b[a.size()],x;

        v[0]=a[0];
        b[0]=a[x-1];
        x=a.size();
        b[x-1]=a[x-1];
        for(int i=1;i<x;i++)
        {
            if(max(a[i],a[i-1])>v[i-1])
                v[i]=max(a[i],a[i-1]);
            else
                v[i]=v[i-1];
    
           
    
        }
    
        for(int i=x-1;i>=0;i--)
        {
           if(max(a[i],a[i+1])>v[i+1])
                v[i]=max(a[i],a[i+1]);
            else
                v[i]=v[i+1];
    
    
        }
    
        int c=0;
        for(int i=0;i<x;i++)
        {
            c=c+min(b[i],v[i])-a[i];
        }
    
    
        return c;
    }
    

    };


  • 1
    S

    Because in your second for loop, you start i at a.size() - 1, and then try to access element i + 1. Which means you are trying to access a[a.size()] outside the bounds of the array.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.