• + 1 comment

    Hi, yeah I'll explain from top to bottom:

    • sort the array from smallest to biggest
    • the constraints disclose that the answer will be greater than or equal to 2, so i instantiate a variable "ans" equal to 2.
    • "temp" is a temporary answer because we need to calculate the length of subarrays multiple times. If “temp” ends up greater than “ans”, the new “ans” will equal “temp”. (the goal of the question is to find the longest subarray)
    • "benchmark" is the number to find the absolute difference for each number of the sub-array. since we are starting from the first number, the benchmark is pre-set to a[0], the first number
    • in the for loop, you put together all the variables into action. The loop will go through each number in the array and find the absolute difference with “benchmark”. As long as the difference is less than or equal to 1, we will add +=1 to “temp” (we’re building up the length of the subarray)
    • however, if the difference is greater than 1, “temp” will override “ans” if “temp” is greater than “ans”. Then we reset “temp”=1 since we need to count the length of the next subarray. And the new “benchmark” will be the current number of the loop.

    Example:

    a = [1, 1, 2, 3, 3, 4]

    benchmark = a[0] = 1

    ans = 2

    temp = 0

    For loop will find the abs diff of each number by the benchmark. This is what’s going on behind the scenes:

    • abs(a[0] – benchmark) = |1-1| = 0 --- yay! Less than or equal to one, so add 1 to temp. temp = 1
    • abs(a[1] – benchmark) = |1-1| = 0 --- yay! Less than or equal to one, so add 1 to temp. temp = 2
    • abs(a[2] – benchmark) = |2-1| = 1 --- yay! Less than or equal to one, so add 1 to temp. temp = 3
    • abs(a[3] – benchmark) = |3-1| = 2 --- no! Greater than one, so replace “ans” if “temp” is greater (in this case it is, so ans = temp = 3). Now reset temp = 1 and the benchmark now equals current number which is 3. Repeat the process.