I’m kind of stuck with my code and I can’t find where the problem is. My task is to find the closest sum in the array to the x value and amount of indexes to sum must not exceed n-value. Indexes to sum might not be consecutive, so the closest sum might be indexes(0,2,3) instead of (0,1,2). I’ve written some code, but it does not work with n value bigger than 4.
In my code value of sums(n) if called «towns» and x value is called «miles».
Here comes the code
for(int i=0;i<ls.size();i++){
sum=ls.get(i);
counterTowns=1;
if(sum<miles&&counterTowns<towns){
for(int j=i+1;j<ls.size();j++){
sum+=ls.get(j);
counterTowns++;
if(counterTowns==towns){
if(sum<=miles){
if(sum>temp){
result=sum;
}
temp=result;
}
sum=ls.get(i);
counterTowns=1;
if(towns>2){ // I think the problem is in this line
j--;
}
}
}
}
}
So it works just fine for towns<=3, but with bigger amounts it skips some values. I hope my question is clear and if not fell free to ask any questions. Thank you in advance. Peace and love!!!
Aucun commentaire:
Enregistrer un commentaire