登录
OAmaster

An e-commerce company specializes in cards with sports figures on them. Each sport has different categories of cards. For instance, there might be more desirable cards with the most popular sports personalities, others with small pieces of a player's jersey attached, and so on. They have a number of each category of card and want to make some number of packets greater than 1 that each contain equal numbers of each type of card. To do this, they will add more cards of each type until each type can be divided equally among some number of packets. Determine the minimum number of additional cards needed to create a number of packets with equal type distribution. Function Description Complete the function cardPackets in the editor. cardPackets has the following parameter(s): int cardTypes[n]: the quantity available of card type Returns int: the minimum number of additional cards to add

Constraints

  • 1 ≤ n ≤ 10⁵
  • constraints may not be completed

Example 1

Input:

cardTypes = [4, 7, 5, 11, 15]

Output:

4

Explanation: In order to make 2 matching packets, the following numbers of additional cards of each type must be added: [0, 1, 1, 1, 1]. This sums to 4 additional cards. The numbers of cards are [4, 8, 6, 12, 16] and they can be divided evenly among 2 packets. If 3 packets are created, an additional [2, 2, 1, 1, 0] cards are needed, sum = 6 items. This yields quantities [6, 9, 6, 12, 15]. Any number of packets ≥ 2 can be created, but creating 2 packets requires the minimum number of additional cards.

解法

枚举包数 k (从 2 到某上限),对每种卡 add += (k - cardTypes[i] % k) % k;求最小 add。上限取 max(cardTypes) 即可。时间复杂度 O(N · M),M = max card 数。

from typing import List

def cardPackets(cardTypes: List[int]) -> int:
    upper = max(cardTypes)
    best = float('inf')
    for k in range(2, upper + 1):
        add = sum((k - c % k) % k for c in cardTypes)
        if add < best: best = add
    return int(best)
class Solution {
    long cardPackets(int[] cardTypes) {
        int upper = 0;
        for (int c : cardTypes) upper = Math.max(upper, c);
        long best = Long.MAX_VALUE;
        for (int k = 2; k <= upper; k++) {
            long add = 0;
            for (int c : cardTypes) add += (k - c % k) % k;
            if (add < best) best = add;
        }
        return best;
    }
}
class Solution {
public:
    long long cardPackets(vector<int>& cardTypes) {
        int upper = *max_element(cardTypes.begin(), cardTypes.end());
        long long best = LLONG_MAX;
        for (int k = 2; k <= upper; k++) {
            long long add = 0;
            for (int c : cardTypes) add += (k - c % k) % k;
            if (add < best) best = add;
        }
        return best;
    }
};

Start with an infinite two dimensional grid filled with zeros, indexed from (1, 1) at the bottom left corner with coordinates increasing toward the top and right. Given a series of coordinates (r, c), where r is the ending row and c is the ending column, add 1 to each element in the range from (1, 1) to (r, c) inclusive. Once all coordinates are processed, determine how many cells contain the maximal value in the grid. Function Description Complete the function countMax in the editor. countMax has the following parameter(s):

  • String[] upRight: an array of strings made of two space-separated integers representing r and c respectively Returns int: the number of cells that contain the maximal value

Constraints

  • 1 ≤ upRight.length ≤ 10⁵
  • 1 ≤ r, c ≤ 10⁹

Example 1

Input:

upRight = ["1 4", "2 3", "4 1"]

Output:

1

Explanation: The two space-separated integers within each string represent r and c respectively. The following diagrams show each iteration starting at zero. The maximal value in the grid is 3, and there is 1 occurrence at cell (1, 1).

解法

每个区域 (1..r, 1..c) 都从 (1,1) 开始覆盖,所以最大值出现在 (1,1)(被所有操作累加),等于操作数。重叠区域的格子数 = min(r) * min(c),即所有 r 的最小值乘所有 c 的最小值。时间复杂度 O(N)。

from typing import List

def countMax(upRight: List[str]) -> int:
    minR = minC = float('inf')
    for s in upRight:
        r, c = map(int, s.split())
        minR = min(minR, r); minC = min(minC, c)
    return minR * minC
class Solution {
    long countMax(String[] upRight) {
        long minR = Long.MAX_VALUE, minC = Long.MAX_VALUE;
        for (String s : upRight) {
            String[] p = s.split(" ");
            long r = Long.parseLong(p[0]), c = Long.parseLong(p[1]);
            minR = Math.min(minR, r); minC = Math.min(minC, c);
        }
        return minR * minC;
    }
}
class Solution {
public:
    long long countMax(vector<string>& upRight) {
        long long minR = LLONG_MAX, minC = LLONG_MAX;
        for (auto& s : upRight) {
            stringstream ss(s);
            long long r, c;
            ss >> r >> c;
            minR = min(minR, r); minC = min(minC, c);
        }
        return minR * minC;
    }
};

An anagram is a word whose characters can be rearranged to create another word. Given two strings, determine the minimum number of characters in either string that must be modified to make the two strings anagrams. If it is not possible to make the two strings anagrams, return -1. Function Description Complete the function getMinimumDifference in the editor. getMinimumDifference has the following parameter(s):

    1. String[] a: an array of strings
    1. String[] b: an array of strings Returns int[]: the minimum number of characters in either string that needs to be modified to make the two strings anagrams or -1 if it is not possible

Constraints

  • Each string consists of lowercase characters [a-z].
  • 1 ≤ n ≤ 100
  • 0 ≤ |a[i]|, |b[i]| ≤ 10⁴

Example 1

Input:

a = ["tea", "tea", "act"]
b = ["ate", "toe", "acts"]

Output:

[0, 1, -1]

Explanation:

  • a[0] = tea and b[0] = ate are anagrams, so 0 characters need to be modified.
  • a[1] = tea and b[1] = toe are not anagrams. Modify 1 character in either string (o -> a or a -> o) to make them anagrams.
  • a[2] = act and b[2] = acts are not anagrams and cannot be converted to anagrams because they contain different numbers of characters.
  • The return array is [0, 1, -1]

解法

两串长度不同则返回 -1;否则统计字符频次差,最少修改数 = sum(|cnt_a - cnt_b|) / 2。时间复杂度 O(L)。

from typing import List
from collections import Counter

def getMinimumDifference(a: List[str], b: List[str]) -> List[int]:
    res = []
    for s1, s2 in zip(a, b):
        if len(s1) != len(s2):
            res.append(-1)
            continue
        c1, c2 = Counter(s1), Counter(s2)
        diff = sum(abs(c1[k] - c2[k]) for k in set(c1) | set(c2))
        res.append(diff // 2)
    return res
class Solution {
    int[] getMinimumDifference(String[] a, String[] b) {
        int[] res = new int[a.length];
        for (int i = 0; i < a.length; i++) {
            if (a[i].length() != b[i].length()) { res[i] = -1; continue; }
            int[] cnt = new int[26];
            for (char c : a[i].toCharArray()) cnt[c - 'a']++;
            for (char c : b[i].toCharArray()) cnt[c - 'a']--;
            int diff = 0;
            for (int v : cnt) diff += Math.abs(v);
            res[i] = diff / 2;
        }
        return res;
    }
}
class Solution {
public:
    vector<int> getMinimumDifference(vector<string>& a, vector<string>& b) {
        vector<int> res;
        for (size_t i = 0; i < a.size(); i++) {
            if (a[i].size() != b[i].size()) { res.push_back(-1); continue; }
            int cnt[26] = {0};
            for (char c : a[i]) cnt[c - 'a']++;
            for (char c : b[i]) cnt[c - 'a']--;
            int diff = 0;
            for (int v : cnt) diff += abs(v);
            res.push_back(diff / 2);
        }
        return res;
    }
};
Pro 会员

解锁剩余 1 道 OA 真题

开通后立即解锁完整题面 + Python / Java / C++ 三语题解。 全站 165 家公司 · 1000+ 道 OA · 月度更新。