I am trying to convert this code from python to java, I am stuck and need help:
The code finds the longest continuum in the array that the sum of the values in the continuum equal to zero modulo 3, e.g for the array a[]={2,-3,5,7,-20,7}
We have 2-3+5+7-20=-9 so the output is 5,
Python code:
a = [2,-3,5,7,-20,7]
best = 0
bestIndex = -1
dp = [[0,0,0] for i in range(len(a) + 1)]
for i in range(1,len(a) + 1):
r = a[i-1] % 3
for j in range(3):
canSumToJ = dp[i-1][(3 + j - r) % 3] > 0
dp[i][j] = max(1 if r == j else 0
,1 + dp[i-1][(3 + j - r) % 3] if canSumToJ else 0)
bestIndex = i - 1 if dp[i][0] > best else bestIndex
best = max(best,dp[i][0])
print(best,(bestIndex - best + 1, bestIndex)) # (5, (0, 4))
# dp
# => [[0, 0, 0]
# ,[0, 0, 1]
# ,[1, 0, 2]
# ,[0, 3, 2]
# ,[3, 1, 4]
# ,[5, 4, 2]
# ,[3, 6, 5]]
Attempt to convert to Java:
public class mmn123 {
public static void main(String[] args)
{
//int[] a = {1, 3, 3, 3, 3, 1};
int[] a = {2, -3, 5, 7, -20, 7};
int best = 0;
//int bestIndex=-1 ;
int len=a.length;
int r;
int a1[]={0,0,0};
int a2[]={0,0,0};
int a3[]={0,0,0};
int a4[]={0,0,0};
int a5[]={0,0,0};
int a6[]={0,0,0};
int a7[]={0,0,0};
boolean canSumToJ=false;
int [][]dp={a1,a2,a3,a4,a5,a6,a7};
// for i in range(1,len(a) + 1):
for(int i=1;i<len+1;i++)
{
r = a[i-1] % 3;
//for j in range(3):
for(int j=0;j<3;j++)
{
if(dp[i][(3 + j - r) % 3]>0)
canSumToJ =true; ;
if(r==j&&canSumToJ ==true)
dp[i][j] = Math.max(1,1 + dp[i-1][(3 + j - r) % 3]);
if(r!=j&&canSumToJ ==true)
dp[i][j] = Math.max(0,1 + dp[i-1][(3 + j - r) % 3]);
if(r!=j&&canSumToJ ==false)
dp[i][j] = Math.max(0,0);
if(r==j&&canSumToJ ==false)
dp[i][j] = Math.max(1,0);
canSumToJ=false;
}
//canSumToJ=false;
//if (dp[i][0] > best)
//bestIndex = (i - 1);
//else bestIndex;
best = Math.max(best,dp[i][0]);
}
for(int k=0;k<a.length;k++)
{
for(int l=0;l<3;l++)
{
System.out.print(dp[k][l]);
}
System.out.println();
}
System.out.println("best: "+best);
/*
# dp
# => [[0, 0, 0]
# ,[0, 0, 1]
# ,[1, 0, 2]
# ,[0, 3, 2]
# ,[3, 1, 4]
# ,[5, 4, 2]
# ,[3, 6, 5]]
*/
}
}
The outputs are not the same.