educative.io

Educative

Why maxLength calculation is inside the inner loop?

for (int i = 1; i < nums.size(); i++) {

  dp[i] = 1;

  for (int j = 0; j < i; j++) {

    if (nums[i] > nums[j] && dp[i] <= dp[j]) {

      dp[i] = dp[j] + 1;

      //maxLength = max(maxLength, dp[i]); why inside the loop??

    }

  }

  maxLength = max(maxLength, dp[i]); // putting the check outside will avoid unnecessary check.

}

because If the If condition is true then we are updating the value of dp[i] and then using it for max length. otherwise we are not checking it. If we do this out of the inner loop it will do it once the loop is completed and we can’t check it on the update value of dp[i]