Problem · Heap

Find Sum Weight

Learn this problem
MediumJCJPMorgan ChaseOA

Problem statement

Stacey is coordinating a beach clean-up project with her university's Women in STEM Outreach branch. The beach is covered with tin cans of varying weights arranged in a single line, indexed from 0 to n - 1.

For each selection:

  1. She identifies the lightest remaining can, with weight w.
  2. She uses the scooper to pick up that can along with its two current adjacent cans, or all available adjacent cans if it is at an edge.
  3. She continues this process until there are no cans left on the beach.

If multiple remaining cans have the lightest weight, Stacey selects the one with the smallest original index.

Determine the sum of the weights of the lightest cans she selects.

Function

findSumWeight(cans: int[]) → int

Examples

Example 1

cans = [5, 4, 1, 3, 2]return = 3

Let n = 5 and cans = [5, 4, 1, 3, 2].

  • The lightest can has weight 1. Remove it together with its current neighbors 4 and 3, leaving [5, 2].
  • The lightest remaining can has weight 2. Remove it together with its available neighbor 5.

Hence, the sum of the selected lightest weights is 1 + 2 = 3.

More JPMorgan Chase problems

drafts saved locally
public int findSumWeight(int[] cans) {
    // write your code here
}
cans[5, 4, 1, 3, 2]
expected3
checking account