I am trying to submit the same code as in the video, on leetcode but its giving wrong output.Please check.
My code:
Not able to submit the code
the reason for that is because you dont submit the whole code, just the function that is asked in leetcode. This function gets its input output via invisible backend code for main and input/output which if you also provide also leads to error.
The function signature given on leetcode is
class Solution {
public:
int maxProduct(vector& nums) { }
};
You have to code within this signature. You cannot submit the whole code as you do on ide.codingblocks.com
Ya i know that, i was submitting only the logic part, the problem is on running for the input [-1,-1,0] , maxproduct is 1 but according to the logic in the video , there isn’t any positive element so it returns 0.
Give me the code you have submitted on leetcode then
if(nums.size() == 1 ) return nums[0];
int pp = 1 , np = 1 , maxVal = INT_MIN;
bool hasPos = false , hasZero = false;
for (auto i : nums ) {
if ( i > 0 ) {
hasPos = true ;
pp = pp * i ;
if (np != 1 ) {
np = np * i ;
}
}
else if (i < 0 ) {
int temp = pp ;
pp = max(1 , np * i );
np = temp * i ;
}
else {
np = pp = 1;
hasZero = true ;
}
if(maxVal < pp ) maxVal = pp ;
}
if (maxVal == 1 ) {
if (hasPos) return maxVal;
if (hasZero) return 0 ;
}
return maxVal;
}
The reason you are getting wrong answer on input [-1,-1,0] is because leetcode has not mentioned any constraint of haivng positive numbers. According to them the answer is 1 which is right. However your video has implemented this constraint while solving the question.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.