-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathcalculateSumAndProduct.js
More file actions
39 lines (32 loc) · 931 Bytes
/
calculateSumAndProduct.js
File metadata and controls
39 lines (32 loc) · 931 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Calculate the sum and product of integers in a list
*
* Note: the "sum" is every number added together
* and the "product" is every number multiplied together
* so for example: [2, 3, 5] would return
* {
* "sum": 10, // 2 + 3 + 5
* "product": 30 // 2 * 3 * 5
* }
*
* Time Complexity:
* Space Complexity:
* Optimal Time Complexity:
*
* @param {Array<number>} numbers - Numbers to process
* @returns {Object} Object containing running total and product
*/
export function calculateSumAndProduct(numbers) {
// In this case, there is no changes in the functionality that can change the time complexity as the complexity is already O(n) and only extra space is used.
// In this case, I can just make the code easier to read and cleaner.
let sum = 0;
let product = 1;
for (const num of numbers) {
sum += num;
product *= num;
}
return {
sum: sum,
product: product,
};
}