Sum Elements Greater Than K — Problem Statement & Solution Guide
Problem Description
Given an array of integers nums and a threshold value K, calculate and return the total sum of all elements that are strictly greater than K.
Examples
Input
[1, 2, 3, 4, 5], K = 3
Output
9
Explanation: Step-by-step: with input [1, 2, 3, 4, 5] and K = 3, we filter out elements less than or equal to 3, giving us [4, 5], then sum these elements, resulting in 4 + 5 = 9
Input
[10, 20, 30], K = 15
Output
50
Explanation: Step-by-step: with input [10, 20, 30] and K = 15, we filter out elements less than or equal to 15, giving us [20, 30], then sum these elements, resulting in 20 + 30 = 50
Constraints
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
- -10^4 <= K <= 10^4
Optimal Approach & Strategy
Single-pass linear scan O(N) time and O(1) auxiliary space.
Brute Force Approach
Iterate through all array elements and accumulate values > K in linear time O(N).
Verified Code Solutions
function solution(nums, K) { return nums.filter(num => num > K).reduce((a, b) => a + b, 0); }class Solution { public: int solution(vector<int>& nums, int K) { int sum = 0; for (int num : nums) if (num > K) sum += num; return sum; } };class Solution { public int solution(int[] nums, int K) { int sum = 0; for (int num : nums) if (num > K) sum += num; return sum; } }def solution(nums, K): return sum(num for num in nums if num > K)function solution(nums, K) { return nums.filter(num => num > K).reduce((a, b) => a + b, 0); }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.