Iterative Stack Horizon — Problem Statement & Solution Guide
Problem Description
Given an array of integers, find the sum of the two largest distinct numbers in the array.
Examples
Input
[1, 2, 3, 4, 5]
Output
9
Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we first sort the array in descending order to get [5, 4, 3, 2, 1], then we add the first two distinct numbers which are 5 and 4, giving output 9
Input
[10, 20, 30, 40, 50]
Output
90
Explanation: Step-by-step: with input [10, 20, 30, 40, 50], we first sort the array in descending order to get [50, 40, 30, 20, 10], then we add the first two distinct numbers which are 50 and 40, giving output 90
Constraints
- 1 <= N <= 10^5
- -10^9 <= arr[i] <= 10^9
- Time Complexity expected: O(N) or O(N log N)
- Space Complexity expected: O(1) or O(N)
Optimal Approach & Strategy
Use Character Frequency Map to maintain a running state in O(N) time and O(1) auxiliary space.
Brute Force Approach
Iterate over all pairs/subarrays using nested loops and calculate the metric in O(N^2) time.
Verified Code Solutions
function solution(nums) {
nums = [...new Set(nums)].sort((a, b) => b - a);
return nums[0] + nums[1];
}class Solution {
public:
int solution(vector<int>& nums) {
sort(nums.rbegin(), nums.rend());
int max1 = INT_MIN;
int max2 = INT_MIN;
for (int num : nums) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2 && num != max1) {
max2 = num;
}
}
return max1 + max2;
}
};class Solution {
public int solution(int[] nums) {
Arrays.sort(nums);
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2 && num != max1) {
max2 = num;
}
}
return max1 + max2;
}
}def solution(nums):
nums = sorted(set(nums), reverse=True)
return nums[0] + nums[1]function solution(nums) {
nums = [...new Set(nums)].sort((a, b) => b - a);
return nums[0] + nums[1];
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.