Sobes.tech
Middle+

In array A, there are prices for N items. There are K coupons that reduce the item's price by X. If t coupons are applied to an item with price a, its final cost will be max(a - t*X, 0). Return the minimum amount of money needed to buy all items. A = 8, 3, 10, 5, 13 K = 4 X = 7 result=12 --- Given an array a of n positive integers, are there three distinct indices i, j, k such that the sum a[i]+a[j]+a[k] ends with the digit m? For example, for m = 3 solve([20, 22, 19, 84]) => true // 20 + 84 + 19 = 123 solve([1,2,3]) => false

sobes.tech AI

Answer from AI

The task consists of two parts, which we will solve sequentially.


Part 1: Minimum sum with coupons

Given: an array of prices A, number of coupons K, each coupon reduces the price by X.

Solution idea:

  • To minimize the total sum, use coupons on the most expensive items as much as possible.
  • Sort the array of prices in descending order.
  • Distribute coupons starting from the most expensive item, applying the maximum possible number of coupons (until the price becomes 0 or coupons run out).

Example in C#:

int MinCost(int[] A, int K, int X) {
    Array.Sort(A);
    Array.Reverse(A);
    int totalCost = 0;
    foreach (var price in A) {
        int couponsToUse = Math.Min(K, price / X);
        K -= couponsToUse;
        int finalPrice = price - couponsToUse * X;
        totalCost += finalPrice;
    }
    return totalCost;
}

// For A = [8,3,10,5,13], K=4, X=7
// Result will be 12

Part 2: Checking the existence of three indices i, j, k such that their sum ends with m

Idea:

  • Consider the remainders of array elements modulo 10 (since we're interested in the last digit of the sum).
  • Iterate over all triplets of remainders and check if there are corresponding elements in the array.

Example in C#:

bool Solve(int[] a, int m) {
    int n = a.Length;
    int[] modCount = new int[10];
    foreach (var val in a) modCount[val % 10]++;

    for (int i = 0; i < 10; i++) {
        for (int j = i; j < 10; j++) {
            for (int k = j; k < 10; k++) {
                if ((i + j + k) % 10 == m) {
                    // Check if there are enough elements for three different indices
                    int[] counts = new int[10];
                    counts[i]++; counts[j]++; counts[k]++; 
                    bool enough = true;
                    for (int x = 0; x < 10; x++) {
                        if (counts[x] > modCount[x]) {
                            enough = false;
                            break;
                        }
                    }
                    if (enough) return true;
                }
            }
        }
    }
    return false;
}

Example:

  • solve([20, 22, 19, 84], 3) => true (20+84+19=123)
  • solve([1,2,3], 3) => false