Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Dynamic Programming - Part sum of elements JavaScript
In this problem, we calculate the sum of all elements except one element at each step, creating an array of partial sums. We'll implement this using JavaScript array methods and dynamic programming concepts.
Problem Statement
Given an array of n elements, generate an array containing:
- The sum of all elements
- The sum of all elements except the first element
- The sum of all elements except the second element
- And so on for each element
Algorithm
Step 1: Calculate the total sum of all elements in the array.
Step 2: Create a result array starting with the total sum.
Step 3: For each element in the original array, subtract that element from the total sum.
Step 4: Add each partial sum to the result array.
Implementation
// Input array
const arr = [1, 2, 3, 4, 5];
// Function to calculate sum of array elements
const sumArray = (arr = []) => arr.reduce((a, b) => a + b, 0);
// Function to calculate partial sums
const sumWithoutOne = (arr = []) => {
const totalSum = sumArray(arr);
const result = [totalSum]; // Start with total sum
// Calculate sum excluding each element
for (let i = 0; i < arr.length; i++) {
const partialSum = totalSum - arr[i];
result.push(partialSum);
}
return result;
};
console.log("Original array:", arr);
console.log("Partial sums:", sumWithoutOne(arr));
Original array: [ 1, 2, 3, 4, 5 ] Partial sums: [ 15, 14, 13, 12, 11, 10 ]
Optimized Approach
The above solution can be optimized by avoiding the slice operations:
const optimizedPartialSums = (arr) => {
const totalSum = arr.reduce((sum, num) => sum + num, 0);
// Create result array with total sum first
const result = [totalSum];
// Add sum excluding each element
arr.forEach(num => result.push(totalSum - num));
return result;
};
const numbers = [10, 20, 30, 40];
console.log("Input:", numbers);
console.log("Partial sums:", optimizedPartialSums(numbers));
Input: [ 10, 20, 30, 40 ] Partial sums: [ 100, 90, 80, 70, 60 ]
Step-by-Step Example
For array [1, 2, 3, 4, 5]:
- Total sum: 1+2+3+4+5 = 15
- Excluding 1: 15-1 = 14
- Excluding 2: 15-2 = 13
- Excluding 3: 15-3 = 12
- Excluding 4: 15-4 = 11
- Excluding 5: 15-5 = 10
- Result: [15, 14, 13, 12, 11, 10]
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Using slice operations | O(n²) | O(n) |
| Optimized approach | O(n) | O(n) |
The optimized approach calculates the total sum once (O(n)) and then generates partial sums by simple subtraction (O(n)), resulting in overall O(n) time complexity.
Conclusion
This dynamic programming approach efficiently calculates partial sums by leveraging the total sum. The optimized solution reduces time complexity from O(n²) to O(n) while maintaining O(n) space complexity.
