BackmediumTwo Pointers Microsoft

Galactic Supply Chain Optimization Solution

Problem Statement

Given an array of integers, find the optimal partition point that minimizes the absolute difference in the total weight of gems delivered to each station.

Example 1
Input
[13, 41, 22, 57, 11, 9, 7, 5, 3, 1]
Output
6

Explanation: Step 1: Sort the array in descending order. [57, 41, 22, 13, 11, 9, 7, 5, 3, 1]. Step 2: Initialize two pointers, i and j, at the start and end of the array. i = 0, j = 9. Step 3: Initialize two variables, left_sum and right_sum, to 0. left_sum = 0, right_sum = 0. Step 4: Move the pointers towards each other, and at each step, add the current element to the left_sum or right_sum. Step 5: If the absolute difference between left_sum and right_sum is less than the current minimum difference, update the minimum difference and the optimal partition point. Step 6: Return the optimal partition point.

Example 2
Input
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Output
not 4

Explanation: Step 1: Sort the array in descending order. [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]. Step 2: Initialize two pointers, i and j, at the start and end of the array. i = 0, j = 9. Step 3: Initialize two variables, left_sum and right_sum, to 0. left_sum = 0, right_sum = 0. Step 4: Move the pointers towards each other, and at each step, add the current element to the left_sum or right_sum. Step 5: If the absolute difference between left_sum and right_sum is less than the current minimum difference, update the minimum difference and the optimal partition point. Step 6: Return the optimal partition point.

Constraints

  • 2 <= number of containers <= 100
  • 1 <= weight of each container <= 1000
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