easyIntroduction to ArraysPattern: Array Traversal
Sum of Elements Greater Than K Solution
Problem Statement
Given an array of integers `nums` and an integer `k`, your task is to calculate the total sum of all elements in `nums` that are strictly greater than `k`.
Examples
Example 1:
Input:quantities = [10, 75, 20, 80, 45]
Output:undefined
Explanation: The quantities greater than 27 are 75, 80, and 45. Their sum is 75 + 80 + 45 = 200.
Example 2:
Input:quantities = [5, 15, 25, 30]
Output:undefined
Explanation: The only quantity greater than 27 is 30. Its sum is 30.
Example 3:
Input:quantities = [10, 20, 27]
Output:undefined
Explanation: No quantities in the array are greater than 27. The sum is 0.
Constraints
- `0 <= nums.length <= 10^5`
- `-10^9 <= nums[i] <= 10^9`
- `-10^9 <= k <= 10^9`
Time: O(N) Space: O(1)
The most optimal approach for this problem is a single pass iteration through the array. We initialize a sum variable to zero and iterate through each number, accumulating only those that are strictly greater than 'k'. This method is optimal because we must examine every element at least once to determine if it meets the criteria, resulting in O(N) time complexity.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
import sys
def sum_elements_greater_than_k(nums, k):
"""
Calculates the total sum of all elements in nums that are strictly greater than k.
Args:
nums (list[int]): An array of integers.
k (int): An integer threshold.
Returns:
int: The sum of elements strictly greater than k.
"""
total_sum = 0
for num in nums:
if num > k:
total_sum += num
return total_sum
def main():
# Read the array of integers from stdin
# Example: "1 2 3 4 5"
nums_str = sys.stdin.readline().strip()
nums = list(map(int, nums_str.split()))
# Read the integer k from stdin
# Example: "3"
k = int(sys.stdin.readline().strip())
# Calculate the sum
result = sum_elements_greater_than_k(nums, k)
# Print the result to stdout
print(result)
if __name__ == '__main__':
main()
