Skip to content

3471. Find the Largest Almost Missing Integer

  • Time: $O(n)$
  • Space: $O(50) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
 public:
  int largestInteger(vector<int>& nums, int k) {
    if (k == nums.size())
      return ranges::max(nums);
    const vector<int> count = getCount(nums);
    if (k == 1)
      return maxUnique(nums, count);
    return max(count[nums.front()] == 1 ? nums.front() : -1,
               count[nums.back()] == 1 ? nums.back() : -1);
  }

 private:
  // Returns the maximum unique integer in nums if any. Otherwise, returns -1.
  int maxUnique(const vector<int>& nums, const vector<int>& count) {
    int maxUnique = -1;
    for (const int num : nums)
      if (count[num] == 1)
        maxUnique = max(maxUnique, num);
    return maxUnique;
  }

  vector<int> getCount(const vector<int>& nums) {
    constexpr int kMax = 50;
    vector<int> count(kMax + 1);
    for (const int num : nums)
      ++count[num];
    return count;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int largestInteger(int[] nums, int k) {
    if (k == nums.length)
      return Arrays.stream(nums).max().getAsInt();
    int[] count = getCount(nums);
    if (k == 1)
      return maxUnique(nums, count);
    return Math.max(count[nums[0]] == 1 ? nums[0] : -1,
                    count[nums[nums.length - 1]] == 1 ? nums[nums.length - 1] : -1);
  }

  // Returns the maximum unique integer in nums if any. Otherwise, returns -1.
  private int maxUnique(int[] nums, int[] count) {
    return Arrays.stream(nums).filter(num -> count[num] == 1).max().orElse(-1);
  }

  private int[] getCount(int[] nums) {
    final int MAX = 50;
    int[] count = new int[MAX + 1];
    for (final int num : nums)
      ++count[num];
    return count;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def largestInteger(self, nums: list[int], k: int) -> int:
    if k == len(nums):
      return max(nums)
    count = collections.Counter(nums)
    if k == 1:
      return max([num for num in nums if count[num] == 1], default=-1)
    return max(
        nums[0] if count[nums[0]] == 1 else -1,
        nums[-1] if count[nums[-1]] == 1 else -1
    )