No need abs() for returning result


For the last line of the code, I don’t think we need abs(), i.e.
return sum2 - sum1 instead of return abs(sum2 - sum1)

because sum1 <= sum//2 = (sum1+sum2)//2, then sum2 >= sum1

Is that correct?

Hi Jing,

In the given solution code, we’re using the following line of code:
return abs(sum1 - sum2)

Where we’re using sum1-sum2 not sum2-sum1.

When we do a recursive call like the following:

diff1 = can_partition_recursive(
    num, currentIndex + 1, sum1 + num[currentIndex], sum2)

The sum1 is greater than the sum2.

But when we’re doing a recursive call like the following:

  diff2 = can_partition_recursive(
    num, currentIndex + 1, sum1, sum2 + num[currentIndex])

The sum2 is greater than sum1, which can give us the negative value.

We’re using the abs() function to make that negative value positive, which seems necessary here to avoid any wrong answer.

I hope this answers your question.

Thank you!