Why this C++ code get "Wrong answer" when the input is [1,1,1]? I have run it in VS2010,the answer is right.


  • 0
    Z

    class Solution {
    public:

    int mymax(int a,int b)
    {
        return a>b?a:b;
    }
    
    int reverserob(vector<int>& nums,int startindex,int sum,bool select[],bool canselect[])
    {
        if(startindex==0)
        {
            int sum1=reverserob(nums,1,0,select,canselect);
            
            select[0]=true;
            canselect[1]=false;
            int sum2=reverserob(nums,2,nums[0],select,canselect);
            
            return mymax(sum1,sum2);
        }
        
        if(startindex<nums.size()-1)
        {
            if(((!select[startindex-1]) && (!select[startindex+1])) && (canselect[startindex]))
            {
                int sum1=reverserob(nums,startindex+1,sum,select,canselect);
                
                select[startindex]=true;
                canselect[startindex-1]=canselect[startindex+1]=false;
                int sum2=reverserob(nums,startindex+2,sum+nums[startindex],select,canselect);    
                
                return mymax(sum1,sum2);
            
            }
            else
                return reverserob(nums,startindex+1,sum,select,canselect);
        }
        
        if(startindex==nums.size()-1)
        {
            if((!select[startindex-1])&& canselect[startindex] )
            {
                
                int sum2=sum+nums[startindex];    
                
                return sum2;
                
            }
            else
               return sum;
        }
    }
    
    int rob(vector<int>& nums) {
        if(nums.size()<=0)
           return 0;
        else
          if(nums.size()==1)
            return nums[0];
          else if(nums.size()==2)
            return mymax(nums[0],nums[1]);
            
        bool *select=new bool[nums.size()];
        for(int i=0;i<nums.size();++i)
           select[i]=false;
    
        bool *canselect=new bool[nums.size()];
        for(int i=0;i<nums.size();++i)
           canselect[i]=true;
    
        
        return  reverserob(nums,0,0,select,canselect);
        
    }
    

    };


Log in to reply
 

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