BackmediumGreedyuncategorizedmedium

Optimal Magical Combination Solution

Problem Statement

You are given an integer array ingredients. From this array you must pick a non‑empty subset of elements (the order does not matter) such that the sum of the chosen elements is as large as possible. Return that maximum achievable sum. The subset may contain any number of elements from one up to the full length of the array, but it cannot be empty.

Example 1
Input
[5, -2, 3, -1]
Output
8

Explanation: The best choice is to take the elements 5 and 3. Their sum is 5 + 3 = 8, which is larger than any other non‑empty subset (e.g., 5 alone gives 5, 5 + -2 + 3 = 6, etc.).

Example 2
Input
[-4, -7, -2]
Output
-2

Explanation: All numbers are negative, so the maximum sum is obtained by selecting the single largest element, -2. Any subset containing more than one element would produce a smaller (more negative) sum.

Example 3
Input
[0, -1, 2, 4, -3]
Output
6

Explanation: Choosing the elements 2 and 4 yields the sum 2 + 4 = 6. Adding 0 does not change the sum, while adding any negative number would decrease it, so the optimal subset is {2,4}.

Constraints

  • 1 <= ingredients.length <= 100000
  • -10^9 <= ingredients[i] <= 10^9
  • The answer fits in a 64‑bit signed 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

Optimal Magical Combination — Problem Statement & Solution Guide

GreedyMediumMixed
TimeO(n)
|
SpaceO(1)

Problem Description

You are given an integer array ingredients. From this array you must pick a non‑empty subset of elements (the order does not matter) such that the sum of the chosen elements is as large as possible. Return that maximum achievable sum. The subset may contain any number of elements from one up to the full length of the array, but it cannot be empty.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Optimal Magical Combination"

medium

WHY DOES IT MATTER?

This pattern is a classic example of greedy selection based on sign, which is a fundamental concept in algorithm design. Recognizing when a simple property (positivity) guarantees optimality saves exponential time.

OPTIMIZATION CHALLENGE

The key insight is that the subset sum problem collapses to a linear scan when the objective is to maximize sum without constraints, eliminating the need for exponential enumeration.

REAL-WORLD CONNECTION

In distributed systems, deciding which microservices to activate based on positive performance impact mirrors this pattern, where you enable all services that improve throughput and disable those that degrade it.

During interviews, emphasize the edge case of all negatives and explain why you return the maximum element, showing awareness of boundary conditions.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem reduces to selecting a subset of integers that maximizes the sum. A naive approach would enumerate all 2^n subsets, which is infeasible for n>30. The optimal solution observes that adding a positive number always increases the sum, while adding a negative number decreases it. Therefore, the maximum sum is achieved by summing all positive elements. If the array contains no positive numbers, the best we can do is pick the single largest (least negative) element, because any additional negative numbers would only reduce the sum further. This greedy strategy runs in linear time and uses constant extra space.

The key insight is that the objective function (sum) is linear and unconstrained, so the optimal subset is determined solely by the sign of each element. This eliminates the need for dynamic programming or combinatorial enumeration, turning an exponential problem into a simple linear scan.

Interview Questions on This Problem

Q1What is the time complexity of the optimal solution for this problem and why does it work?

The optimal solution runs in O(n) time because it requires a single pass through the array to sum positive numbers and track the maximum element. It works because any positive number can only increase the sum, while any negative number would decrease it, so the greedy choice of including all positives and, if none, the largest negative is optimal.

Q2How would you handle an array that contains only negative numbers in an interview setting?

I would explain that if there are no positive numbers, the maximum achievable sum is the largest (least negative) element, because we must choose a non‑empty subset. I would demonstrate this by tracking the maximum during the single pass and returning it when the sum of positives is zero.

Q3Can you relate this problem to a real-world scenario that a fintech company might encounter?

Yes, consider a portfolio of trades where each trade has a projected profit or loss. To maximize expected profit, you would execute all trades with positive expected returns. If all trades are expected to lose money, you would choose the trade with the smallest loss to minimize damage. This mirrors the greedy selection based on sign.

Examples

Example 1

Input

[5, -2, 3, -1]

Output

8

Explanation: The best choice is to take the elements 5 and 3. Their sum is 5 + 3 = 8, which is larger than any other non‑empty subset (e.g., 5 alone gives 5, 5 + -2 + 3 = 6, etc.).

Example 2

Input

[-4, -7, -2]

Output

-2

Explanation: All numbers are negative, so the maximum sum is obtained by selecting the single largest element, -2. Any subset containing more than one element would produce a smaller (more negative) sum.

Example 3

Input

[0, -1, 2, 4, -3]

Output

6

Explanation: Choosing the elements 2 and 4 yields the sum 2 + 4 = 6. Adding 0 does not change the sum, while adding any negative number would decrease it, so the optimal subset is {2,4}.

Constraints

  • 1 <= ingredients.length <= 100000
  • -10^9 <= ingredients[i] <= 10^9
  • The answer fits in a 64‑bit signed integer.

Optimal Approach & Strategy

Traverse the array once, summing positives and tracking the maximum element. If the sum is zero, return the maximum; otherwise return the sum. This is O(n) time and O(1) space.

Brute Force Approach

Enumerate every non-empty subset, compute its sum, and keep track of the maximum. This requires O(2^n) time and O(1) additional space.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function maxSubsetSum(ingredients) {
    let sumPos = 0;
    let maxElem = -Infinity;
    for (const x of ingredients) {
        if (x > 0) sumPos += x;
        if (x > maxElem) maxElem = x;
    }
    return sumPos > 0 ? sumPos : maxElem;
}

Asked in Top Tech Interviews

uncategorizedmediumgeneric

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.