Find the Minimum Amount of Time to Brew Potions - Problem

You are given two integer arrays, skill and mana, of length n and m respectively. In a laboratory, n wizards must brew m potions in order.

Each potion has a mana capacity mana[j] and must pass through all the wizards sequentially to be brewed properly. The time taken by the i-th wizard on the j-th potion is time[i][j] = skill[i] * mana[j].

Important: Since the brewing process is delicate, a potion must be passed to the next wizard immediately after the current wizard completes their work. This means the timing must be synchronized so that each wizard begins working on a potion exactly when it arrives.

Return the minimum amount of time required for all potions to be brewed properly.

Input & Output

Example 1 — Basic Case
$ Input: skill = [2,3,1], mana = [2,3]
Output: 22
💡 Note: Potion 1 (mana=2): Wizard 0 finishes at time 4, Wizard 1 at max(0,4)+6=10, Wizard 2 at max(0,10)+2=12. Potion 2 (mana=3): Wizard 0 finishes at time 4+6=10, Wizard 1 at max(10,10)+9=19, Wizard 2 at max(12,19)+3=22. Final completion time is 22.
Example 2 — Single Wizard
$ Input: skill = [5], mana = [1,2,3]
Output: 30
💡 Note: Single wizard processes potions sequentially: 5*1 + 5*2 + 5*3 = 5 + 10 + 15 = 30
Example 3 — Single Potion
$ Input: skill = [1,2,3], mana = [4]
Output: 24
💡 Note: One potion through three wizards: Wizard 0 finishes at time 4, Wizard 1 at max(0,4)+8=12, Wizard 2 at max(0,12)+12=24. Total completion time is 24.

Constraints

  • 1 ≤ n, m ≤ 103
  • 1 ≤ skill[i], mana[j] ≤ 104

Visualization

Tap to expand
Minimum Time to Brew Potions INPUT skill[] - Wizard Skills 2 3 1 W0 W1 W2 mana[] - Potion Mana 2 3 P0 P1 time[i][j] = skill[i] * mana[j] P0 P1 W0 4 6 W1 6 9 W2 2 3 ALGORITHM STEPS 1 Compute Prefix Sums prefix[i] = sum of times for wizards 0..i 2 Track Start Times Each potion starts when all wizards are ready 3 Compute Max Delays Find optimal start for each new potion 4 Sum Total Time Last potion end time is the answer Timeline Visualization 4 6 2 6 9 3 P0 (blue) P1 (purple) FINAL RESULT Output 12 Total time units Time Breakdown: Potion 0: t=0 to t=12 (0+4+6+2 = 12) Potion 1: t=3 to t=12 (3+6+9+3 = 21 end) OK - DONE Key Insight: Prefix sum optimization allows O(n*m) computation by tracking cumulative wizard processing times. Each potion must wait until ALL wizards finish with previous potion at their respective stages. The optimal start time ensures no wizard is idle while maintaining sequential potion flow. TutorialsPoint - Find the Minimum Amount of Time to Brew Potions | Prefix Sum Optimization
Asked in
Google 25 Amazon 20 Microsoft 15
23.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen