Hey LeetCode Community,
I recently came across an interesting and tricky array optimization problem in a Zomato Online Assessment for a Fresher/SDE-1 role. I wanted to share the problem statement
Problem Description:
Zomato is optimizing its automated warehouse layout. The warehouse consists of N bays arranged in a straight line, represented by a 0-indexed integer array packages, where packages[i] denotes the number of food package units stored at bay i.
The robot starts its operation at one of the two ends of the warehouse line (either at bay 0 or at bay N-1). It must choose one starting base station and use it for all operations; it cannot switch its base station halfway through.
To clear the packages, the robot performs sequential delivery trips under the following rules:
In a single trip, the robot starts at its base station, moves to a targeted bay i, picks up at most 1 unit of a package from that bay, and returns to the base station.
While traveling to a target bay i, the robot can also pick up at most 1 unit from any other intermediate bay it passes along the way for free, provided that bay still has packages left.
The travel cost of a single trip is equal to the 1-indexed distance from the robot's chosen base station to the furthest bay i it visits on that trip.
(1)If the base station is at index 0: Traveling to index i costs i + 1.
(2) If the base station is at index N-1: Traveling to index i costs N - i.
The handling cost to load and unload a single unit of any package is always 1 unit of cost.
Your task is to return the minimum total cost (Total Travel Cost + Total Handling Cost) required to completely clear all package units from the warehouse.
Constraints
1 ≤ N ≤ 10⁵
0<=packages[i]<10^9
Sample Test Cases
Sample Input 1:
packages = [1, 2, 3]
Sample Output 1: 12
Explanation:
Handling Cost: Total units = 1 + 2 + 3 = 6.
Strategy A (Base at index 2 - Right End):
Trip 1: Go to index 0 (distance 3). Array becomes [0, 1, 2]. Cost = 3.
Trip 2: Go to index 1 (distance 2). Array becomes [0, 0, 1]. Cost = 2.
Trip 3: Go to index 2 (distance 1). Array becomes [0, 0, 0]. Cost = 1.
Travel Cost = 3 + 2 + 1 = 6. Total = 6 + 6 = 12.Strategy B (Base at index 0 - Left End): Requires 3 trips to the furthest element (index 2) costing 3 × 3 = 9. Total = 9 + 6 = 15.
Minimum of both is 12.
Sample Input 2:
packages = [7, 4, 7]
Sample Output 2: 39
Explanation:
Handling Cost: Total units = 7 + 4 + 7 = 18.
Travel Cost: Symmetrical array, so both ends give the same travel cost.
To clear the furthest element with 7 items, the robot must make 7 trips all the way to the other end (distance 3).
Travel Cost = 7 × 3 = 21.
Total Cost = 21 + 18 = 39.