BackmediumTwo Pointers Salesforce Paytm

Astronaut Food Rationing Solution

Problem Statement

Given a sorted array of food weights, split the array into two parts such that the total weight in the first part is as close to half the total weight as possible.

Example 1
Input
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output
5

Explanation: Step-by-step: with input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], we first calculate the total weight, which is 55. Then, we calculate the half weight, which is 27.5. We then split the array into two parts such that the total weight in the first part is as close to 27.5 as possible. The split can be done at index 5, resulting in the first part having a total weight of 27, which is as close to 27.5 as possible.

Example 2
Input
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Output
7

Explanation: Step-by-step: with input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], we first calculate the total weight, which is 120. Then, we calculate the half weight, which is 60. We then split the array into two parts such that the total weight in the first part is as close to 60 as possible. The split can be done at index 7, resulting in the first part having a total weight of 59, which is as close to 60 as possible.

Constraints

  • 1 <= weights.length <= 7
  • -1e5 <= weights[i] <= 1e5
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free