BackeasyDynamic ProgrammingSwiggyInfosys

Shortest Path Cost Engine 4 Solution

Problem Statement

You are given an integer N followed by N integers forming the array nums. Your task is to compute the sum of all elements in nums. The intended solution should illustrate the classic knapsack‑style dynamic programming pattern: maintain a one‑dimensional DP array where DP[w] stores the maximum sum achievable with a weight (capacity) w using the processed elements. By initializing the DP array with zero and iterating through each number, the final DP entry corresponding to the total capacity equals the sum of the entire array. Return this sum as a 64‑bit signed integer.

Example 1
Input
3 2 -1 4
Output
5

Explanation: Step 1: Initialize DP[0] = 0. Step 2: Process 2 → DP[2] = max(DP[2], DP[0] + 2) = 2. Step 3: Process -1 → DP[1] = max(DP[1], DP[2] + (-1)) = 1 (or keep 0). Step 4: Process 4 → DP[6] = max(DP[6], DP[2] + 4) = 6 and DP[5] = max(DP[5], DP[1] + 4) = 5. The DP entry for total capacity 5 (2 + (-1) + 4) holds the value 5, which is the sum of the array.

Example 2
Input
5 0 0 0 0 0
Output
0

Explanation: All numbers are zero. The DP array never changes from its initial zero values, so the final sum is 0.

Example 3
Input
4 1000000000 -1000000000 123 -456
Output
-333

Explanation: Processing the first two numbers cancels out to 0. Adding 123 gives DP[123] = 123. Adding -456 updates DP[-333] = -333 (or keeps 0 if negative capacity is ignored, but the total achievable sum after all elements is -333). Hence the overall sum of the array is -333.

Constraints

  • 1 <= N <= 100000
  • -10^9 <= nums[i] <= 10^9
  • The absolute value of the final sum fits within a signed 64‑bit integer.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Shortest Path Cost Engine 4 — Problem Statement & Solution Guide

Dynamic ProgrammingEasyKnapsack State Optimization
TimeO(N·W)
|
SpaceO(W)

Problem Description

You are given an integer N followed by N integers forming the array nums. Your task is to compute the sum of all elements in nums. The intended solution should illustrate the classic knapsack‑style dynamic programming pattern: maintain a one‑dimensional DP array where DP[w] stores the maximum sum achievable with a weight (capacity) w using the processed elements. By initializing the DP array with zero and iterating through each number, the final DP entry corresponding to the total capacity equals the sum of the entire array. Return this sum as a 64‑bit signed integer.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Shortest Path Cost Engine 4"

easy

WHY DOES IT MATTER?

The knapsack DP pattern captures a broad class of resource‑allocation problems where choices are mutually exclusive and must respect a global constraint; mastering it equips engineers to tackle budgeting, scheduling, and capacity‑planning challenges efficiently.

OPTIMIZATION CHALLENGE

The key insight is that the DP state can be collapsed to a single dimension because the transition only depends on the previous row; this reduces space from O(N·W) to O(W) while preserving the optimal substructure.

REAL-WORLD CONNECTION

Think of a cloud‑resource scheduler that must pack virtual machines onto physical hosts without exceeding CPU or memory limits—each VM is an item, the host capacity is the weight, and the DP computes the optimal packing to maximize utilization.

During an interview, write the DP update loop first in plain English, then translate it directly to code; this avoids off‑by‑one errors and makes it easy to explain the reverse‑iteration requirement.

COMPLEXITY AT A GLANCE

⏱ Time:O(N·W)
💾 Space:O(W)

Core Theory — Why This Approach?

The classic knapsack‑style dynamic programming pattern solves optimization problems where a limited resource (capacity) must be allocated among a set of items with individual weights and values. Instead of trying every subset (which is exponential), we build a one‑dimensional DP array where DP[w] records the best achievable value for each possible weight w after processing a prefix of the items. By iterating over items and updating DP in reverse weight order, each state reuses previously computed sub‑solutions, guaranteeing optimality while keeping the computation polynomial. Naïve recursion or brute‑force enumeration explodes because it recomputes the same sub‑problems many times and cannot handle large N or large capacity; DP eliminates this redundancy by memoizing results, turning an O(2^N) search into O(N·W) time, where W is the total capacity or sum of weights. The optimal paradigm thus hinges on recognizing overlapping sub‑problems and optimal substructure, enabling a compact representation of the solution space.

Interview Questions on This Problem

Q1How would you adapt the 0/1 knapsack DP to compute the exact sum of all elements in an array without exceeding a given capacity?

Initialize DP[0] = 0 and DP[w] = -∞ for w>0. For each number v, iterate w from capacity down to v and set DP[w] = max(DP[w], DP[w‑v] + v). After processing all numbers, the answer is the maximum DP[w] where w ≤ capacity, which equals the largest achievable sum without exceeding the limit.

Q2Why does updating the DP array in reverse weight order matter in the 0/1 knapsack implementation?

Reverse iteration ensures that each item is considered only once per capacity state; otherwise, forward updates would allow the same item to be used multiple times, effectively turning the problem into an unbounded knapsack.

Q3Can you reduce the space complexity of the knapsack DP from O(N·W) to O(W) and still retain correctness? Explain how.

Yes. By using a single 1‑D array DP[w] and updating it in reverse weight order for each item, we overwrite only states that depend on the previous item, eliminating the need for a second dimension that tracks the item index.

Examples

Example 1

Input

3
2 -1 4

Output

5

Explanation: Step 1: Initialize DP[0] = 0. Step 2: Process 2 → DP[2] = max(DP[2], DP[0] + 2) = 2. Step 3: Process -1 → DP[1] = max(DP[1], DP[2] + (-1)) = 1 (or keep 0). Step 4: Process 4 → DP[6] = max(DP[6], DP[2] + 4) = 6 and DP[5] = max(DP[5], DP[1] + 4) = 5. The DP entry for total capacity 5 (2 + (-1) + 4) holds the value 5, which is the sum of the array.

Example 2

Input

5
0 0 0 0 0

Output

0

Explanation: All numbers are zero. The DP array never changes from its initial zero values, so the final sum is 0.

Example 3

Input

4
1000000000 -1000000000 123 -456

Output

-333

Explanation: Processing the first two numbers cancels out to 0. Adding 123 gives DP[123] = 123. Adding -456 updates DP[-333] = -333 (or keeps 0 if negative capacity is ignored, but the total achievable sum after all elements is -333). Hence the overall sum of the array is -333.

Constraints

  • 1 <= N <= 100000
  • -10^9 <= nums[i] <= 10^9
  • The absolute value of the final sum fits within a signed 64‑bit integer.

Optimal Approach & Strategy

Use a one‑dimensional DP array where DP[w] stores the maximum achievable sum for weight w, updating it in reverse order for each element. This reduces the time to O(N·W) and space to O(W).

Brute Force Approach

Enumerate every subset of the array and compute its sum, keeping the best sum that respects the capacity. This requires checking 2^N subsets, which is infeasible for large N.

Verified Code Solutions

JavaScript Solution
Time: O(N·W)
function solution(nums) {
   let sum = 0;
   for (let num of nums) {
       sum += num;
   }
   return sum;
}

Asked in Top Tech Interviews

SwiggyInfosys

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.