समस्या
Return the second largest distinct value in the list. Repeated values count once.
Implement second_largest(numbers).
Input
numbers: A list of non-negative integers.
Output
Return the second largest distinct value, or -1 if it doesn't exist.
सीमाएँ
0 ≤ length ≤ 100,000; 0 ≤ each value ≤ 10⁹
उदाहरण
इनपुट:
numbers = [4, 9, 7, 9]
अपेक्षित आउटपुट:
expected = 7
इनपुट:
std::vector<long long> numbers = {4, 9, 7, 9};
अपेक्षित आउटपुट:
long long expected = 7;
इनपुट:
long[] numbers = new long[] {4, 9, 7, 9};
अपेक्षित आउटपुट:
long expected = 7;
व्याख्या
Distinct values are 9, 7, 4; the second largest is 7.
इनपुट:
numbers = [5, 5]
अपेक्षित आउटपुट:
expected = -1
इनपुट:
std::vector<long long> numbers = {5, 5};
अपेक्षित आउटपुट:
long long expected = -1;
इनपुट:
long[] numbers = new long[] {5, 5};
अपेक्षित आउटपुट:
long expected = -1;
व्याख्या
Only one distinct value exists, so the answer is -1.
कैसे हल करें
पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।
संकेत 1
You need the largest and the next different value, not just the top two positions.
संकेत 2
Track two distinct maxima as you scan, updating them when a new value fits above or between them.
संकेत 3
If no second distinct value ever appears, return the special fallback value.
अपेक्षित जटिलता
O(n) time, O(1) extra space
संदर्भ
यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।