Maximum Alternate Chest Sum — Problem Statement & Solution Guide

ArraysMediumMixed
TimeO(N*M)
|
SpaceO(1)

Quick Answer & Algorithm Key Takeaway

Master coding challenges related to Arrays and solve the Maximum Alternate Chest Sum problem optimally.

TopicArrays
PatternMixed
TimeO(N*M)
SpaceO(1)

Problem Description

Given a two‑dimensional integer array chests, each inner array represents a row of values. For a row, define its even‑index sum as the sum of elements whose positions are 0,2,4,… (0‑based). You may select any subset of rows and add their even‑index sums together. Rows whose even‑index sum is less than or equal to zero are never beneficial and can be omitted. Return the maximum total sum achievable.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Maximum Alternate Chest Sum"

medium

WHY DOES IT MATTER?

This pattern exemplifies the "independent sub‑problem aggregation" paradigm where global optimum is the sum of locally optimal, non‑conflicting choices, a cornerstone in greedy algorithms and DP base cases.

OPTIMIZATION CHALLENGE

The key insight is recognizing that rows do not interact, allowing us to replace exponential subset enumeration with a single pass that filters positive contributions, collapsing both time and space to linear bounds.

REAL-WORLD CONNECTION

Think of each row as a microservice reporting profit from even‑indexed transactions; the system only activates services with positive profit, akin to scaling out only profitable instances in a distributed cloud deployment.

During an interview, first state the independence observation, then write a loop that computes the even‑index sum per row and accumulates only if >0 – this shows both analytical clarity and coding efficiency.

COMPLEXITY AT A GLANCE

⏱ Time:O(N*M)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem reduces to a simple aggregation over independent rows. Each row contributes a value equal to the sum of its elements at even positions (0‑based). Because rows are independent, the global optimum is obtained by selecting every row whose contribution is positive – a classic greedy selection on a set of non‑interacting items. A naïve solution might try all subsets of rows, leading to O(2^n) exponential time, which is infeasible for large n. Recognizing the separability lets us replace the exponential search with a linear scan, computing each row’s even‑index sum in O(m) where m is the row length, and then summing only the positive contributions, achieving O(N·M) overall where N is the number of rows.

Interview Questions on This Problem

Q1How would you modify the solution if the definition of a "beneficial" row changed to "even‑index sum greater than a given threshold T"?

Compute each row’s even‑index sum as before, then add it to the answer only if sum > T. The algorithmic complexity remains O(N·M) because the threshold check is O(1) per row.

Q2In a streaming scenario where rows arrive one‑by‑one, how can you maintain the maximum total without storing all rows?

Maintain a running total of positive even‑index sums; for each incoming row compute its even‑index sum and, if positive, add it to the accumulator. No storage of past rows is needed, yielding O(1) extra space.

Q3If the array were three‑dimensional (layers × rows × columns) and you could pick any subset of layers, each layer’s contribution being the sum of its rows’ even‑index sums, does the greedy strategy still hold?

Yes, because layer contributions are independent; you still sum all layer totals that are positive. The algorithm extends by first aggregating each layer’s total (a linear pass) and then adding positive layer totals.

Examples

Example 1

Input

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

Output

14

Explanation: Row0 even‑index sum =5+3=8 (positive). Row1 even‑index sum =-4+(-1)=-5 (negative, skip). Row2 even‑index sum =7+(-3)+2=6 (positive). Total =8+6=14.

Example 2

Input

[[-1,-2],[0],[10,-10,5]]

Output

15

Explanation: Row0 sum=-1 (skip). Row1 sum=0 (skip). Row2 sum=10+5=15 (positive). Total=15.

Example 3

Input

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

Output

8

Explanation: Row0 sum=2+4=6. Row1 sum=1+1=2. Row2 sum=-5+(-5)=-10 (skip). Total=6+2=8.

Constraints

  • 1 <= chests.length <= 100000
  • 1 <= chests[i].length <= 100000
  • Sum of all chests[i].length across rows <= 200000
  • -10^9 <= chests[i][j] <= 10^9

Optimal Approach & Strategy

Compute each row’s even‑index sum once, add it to the answer only if it’s positive – linear time.

Brute Force Approach

Enumerate every subset of rows, compute the total even‑index sum for each subset, and keep the maximum – exponential time.

Code Solutions

JavaScript Solution
Time: O(N*M)
const fs = require('fs');
const data = fs.readFileSync(0,'utf8').trim().split(/\s+/).map(Number);
let idx = 0;
function maximumAlternateChestSum(chests){
    let total = 0;
    for(const row of chests){
        let sum = 0;
        for(let i=0;i<row.length;i+=2) sum += row[i];
        if(sum>0) total += sum;
    }
    return total;
}
if(data.length===0){process.exit(0);} 
const n = data[idx++];
let chests = [];
for(let i=0;i<n;i++){
    const m = data[idx++];
    const row = [];
    for(let j=0;j<m;j++) row.push(data[idx++]);
    chests.push(row);
}
console.log(maximumAlternateChestSum(chests));

Asked in Top Tech Interviews

Oracle

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.