JPMORGAN Coding Question – Solved

3 Live
Stacey is coordinating a beach clean-up event with her university's Women in STEM Charity branch. The beach is covered with tin cans of varying weights arranged in a single line, indexed from 0 to n-1. Stacey uses a scooper that can pick up three adjacent cans at a time. 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 adjacent cans (or fewer if at the edge) 3. She continues this process until there are no cans left on the beach If multiple cans have the lightest weight, Stacey selects the one with the smallest index. If a can has fewer than two adjacent cans, she removes the available adjacent cans. Determine the sum of the weights of the lightest cans she picks in each selection. Example Let there be n = 5 cans on the beach with weights represented by cans = [5, 4, 1, 3, 2]. - First, choose the minimum weight, i.e., 1, and add that weight to the total. The cans with weights 4, 1, and 3 are removed. The array of cans is now [5, 2]. - Then, choose the minimum weight, i.e., 2, and add that weight to the total. The cans with weights 2 and 5 are removed. There are no more cans left. Hence, the total is 1 + 2 = 3. Function Description Complete the function findTotalWeight in the editor with the following parameter: int cans[n]: the weights of the cans on the beach Returns int: the sum of the minimum-weight cans at each selection Constraints Β· 3 ≀ length of cans ≀ 2000 Β· 1 ≀ cans[i] ≀ 10^5 Sample Case 0 Input cans = [6, 4, 9, 10, 34, 56, 54] Output 68 Explanation - First, select the minimum weight, 4. Its adjacent cans (6 and 9) are also removed β†’ [10, 34, 56, 54] - Next, select 10. Its adjacent (34) is also removed β†’ [56, 54] - Finally, select 54. Its adjacent (56) is removed β†’ [] Sum = 4 + 10 + 54 = 68 Sample Case 1 Input cans = [132, 45, 65, 765, 345, 243, 75, 67] Output 1120 Explanation - Select 45 β†’ remove 132, 45, 65 β†’ [765, 345, 243, 75, 67] - Select 67 β†’ remove 75, 67 β†’ [765, 345, 243] - Select 243 β†’ remove 345, 243 β†’ [765] - Select 765 β†’ remove 765 β†’ [] Sum = 45 + 67 + 243 + 765 = 1120

Asked in: JPMORGAN

Image of the Question

Question Image Question Image Question Image Question Image

All Testcases Passed βœ”



Passcode Image

Solution


Please login to view the solution


Related Questions

| Perform a series of operations on a given array of integers. Each operation con… |
| Data scientists at Amazon are working on a utility for detecting similar passwo… |
| To be efficient, Amazon must optimally distribute parcels among their delivery … |
| The Amazon warehouse receives a multitude of packages every day, each assigned … |
| As an operations engineer at Amazon, you are responsible for organizing the dis… |
| Amazon Books is a retail store that sells the newly launched novel "The Story o… |