My code worked on my PC but failed on OJ, why?


  • 0
    T

    My code worked as expected on my PC but got wrong answer for the case:

    Submission Result: Wrong Answer
    Input: [0,2,0]
    Output: 2
    Expected: 0

    Seems no global or static variable in my code, neither run time error. Could someone help take a look at the problem? Thanks.

    #include <iostream>
    #include <string>
    #include <map>
    #include <vector>
    #include <algorithm>
    #include <utility>
    
    using namespace std;
    class Solution {
    public:
        int trap(int A[], int n) {
           int  w = 0;
           int left, right, mid, pos;
           bool lflag, rflag;
           lflag = rflag = false;
    
           left = 0;
           while(left + 1< n) {
               while(left+1<n && A[left] == A[left+1]) 
                   left++;
    
    
               right=mid = pos = left;
               while(pos+1<n && A[pos] > A[pos+1]) {
                 pos++;
                 if(!lflag) lflag=true;
               }
               if (!lflag) {
                   left++;
                   continue;
               }
               right = mid = pos;
    
               int i;
               for(i = left+1; i<n&&A[i]<A[left]; i++);
               if (A[i] >= A[left])  {
                   right = i;
                   rflag = true;
               }
               else {
                   while(right+1<n&&A[right] <= A[right+1]) {
                       right++;
                       if(!rflag) rflag=true;
                   }
               }
    
               if(lflag && rflag) {
                   int ceil = min(A[left], A[right]);
                   for(int i = left+1; i < right; i++) { 
                       if (ceil - A[i] > 0)
                           w += (ceil -  A[i]);
                   }
               }
               //cout << left << " " << right << " " << w << endl;
    
               left=right;
               lflag = rflag = false;
           }
    
           return w;
        }
    };
    
    int main() {
        Solution s;
        int *a=new int[12];
        a[0] = 0;
        a[1] = 2;
        a[2] = 0;
        cout <<s.trap(a, 3) << endl;
    }

Log in to reply
 

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