Leetcode 2923. Find Champion I
You are given an array of integers nums
which represents the scores of various players in a game. A Champion player is defined as a player whose score is the strictly greater than all other players’ scores. Your task is to determine the Champion player’s score. If no such player exists (i.e., no single player has a strictly greater score than the others), return -1.
nums
?nums
?Based on typical assumptions in such problems:
nums
can have a length anywhere from 0 to 1000.nums
can be any 32-bit signed integers.maxScore
to keep track of the highest score found, and secondMaxScore
for the second highest score.maxScore
and secondMaxScore
.maxScore
, update secondMaxScore
to be maxScore
and then update maxScore
to be the current score.secondMaxScore
but less than maxScore
, update secondMaxScore
.maxScore
is still greater than secondMaxScore
, then maxScore
is the champion’s score.#include <vector>
#include <algorithm>
using namespace std;
int findChampion(const vector<int>& nums) {
if (nums.empty()) return -1;
int maxScore = INT_MIN;
int secondMaxScore = INT_MIN;
for (int score : nums) {
if (score > maxScore) {
secondMaxScore = maxScore;
maxScore = score;
} else if (score > secondMaxScore && score < maxScore) {
secondMaxScore = score;
}
}
// If secondMaxScore is still INT_MIN, it means there was no second distinct score.
return maxScore > secondMaxScore ? maxScore : -1;
}
int main() {
vector<int> nums = {3, 6, 1, 5};
// Expected output: 6, since 6 is strictly greater than all other scores
int championScore = findChampion(nums);
if (championScore == -1) {
cout << "No single champion found." << endl;
} else {
cout << "Champion's score: " << championScore << endl;
}
return 0;
}
nums
. We only traverse the array once.This approach ensures that we efficiently and correctly determine the Champion’s score or conclude that no Champion exists.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?