I write the following code to find the maximum product subarray:
def ans(arr, n):
M = 1000000007
cur_max = cur_min = ans = arr[0] % M
for i in range(1, n):
tmp = cur_max
cur_max = max(arr[i], cur_min * arr[i]% M, cur_max * arr[i] % M)
cur_min = min(arr[i], cur_min * arr[i] % M, tmp * arr[i] % M)
ans = max(ans, cur_max)
return ans % M
When I use it on
array = [6, -3, -10, 0, 2], I get an answer: 999999989
Whereas, when I change it to
from math import *
def ans(arr, n):
M = 1000000007
cur_max = cur_min = ans = arr[0]
for i in range(1, n):
tmp = cur_max
cur_max = max(arr[i], int(fmod(cur_min * arr[i], M)), int(fmod(cur_max * arr[i], M)))
cur_min = min(arr[i], int(fmod(cur_min * arr[i], M)), int(fmod(tmp * arr[i], M)))
ans = max(ans, cur_max)
return ans
I get the answer: 180
The only change I made was to use the fmod function and then convert it into integers rather than using the mod (%) operator. Why do I get totally different answers?