Sobes.tech
Middle+

Given an array A of N positive numbers, are there three different indices i, j, k such that the sum A[i] + A[j] + A[k] ends with the digit M?

sobes.tech AI

Answer from AI

Task: check if there exist three distinct indices i, j, k such that the sum A[i] + A[j] + A[k] ends with the digit M.

Approach:

  1. Since we are only interested in the last digit of the sum, we can consider all elements modulo 10.
  2. Iterate over all triplets (i, j, k) and check if the sum ends with M.

Example solution in C#:

bool ExistsTripleWithSumEnding(int[] A, int M) {
    int n = A.Length;
    M = M % 10;
    for (int i = 0; i < n - 2; i++) {
        for (int j = i + 1; j < n - 1; j++) {
            for (int k = j + 1; k < n; k++) {
                int sumLastDigit = (A[i] + A[j] + A[k]) % 10;
                if (sumLastDigit == M) {
                    return true;
                }
            }
        }
    }
    return false;
}

For optimization, you can use the frequencies of remainders modulo 10 and check combinations of remainders whose sum modulo 10 equals M, but the basic brute-force approach is suitable for small N.