Minimum Time to Make Array Sum At Most x - Problem

Imagine you have two arrays that represent a dynamic system where values grow over time, but you can strategically reset elements to minimize the total sum.

You're given two 0-indexed integer arrays nums1 and nums2 of equal length. Every second, the system evolves:

  • For all indices 0 โ‰ค i < nums1.length, nums1[i] increases by nums2[i]
  • After this growth, you can choose exactly one index and reset nums1[i] = 0

Your goal is to find the minimum time needed to make the sum of all elements in nums1 less than or equal to x. If it's impossible, return -1.

Example: If nums1 = [1, 2, 3], nums2 = [1, 2, 3], and x = 4, you need to strategically reset elements as they grow to keep the total sum โ‰ค 4.

Input & Output

example_1.py โ€” Basic case
$ Input: nums1 = [1,2,3], nums2 = [1,2,3], x = 4
โ€บ Output: 3
๐Ÿ’ก Note: At each second, we grow all elements and can reset one. To keep sum โ‰ค 4, we need to strategically reset elements with highest growth rates first, taking 3 seconds total.
example_2.py โ€” Already satisfied
$ Input: nums1 = [1,2,3], nums2 = [3,3,3], x = 10
โ€บ Output: 0
๐Ÿ’ก Note: Initial sum is 6, which is already โ‰ค 10, so no time needed.
example_3.py โ€” Impossible case
$ Input: nums1 = [4,4,4], nums2 = [0,0,0], x = 4
โ€บ Output: -1
๐Ÿ’ก Note: No growth occurs, but initial sum (12) > x (4), so it's impossible to achieve the target.

Constraints

  • 1 โ‰ค nums1.length โ‰ค 103
  • 0 โ‰ค nums1[i], nums2[i] โ‰ค 106
  • 1 โ‰ค x โ‰ค 1014
  • nums1.length == nums2.length

Visualization

Tap to expand
Strategic Reset TimingTime 0 (Initial)val:2+5/secval:1+3/secval:3+1/secSum = 6Time 1 (After Growth + Reset)RESETval:0val:4+3/secval:4+1/secSum = 8ร—Time 2val:5+5/secRESETval:0val:5+1/secSum = 10ร—Time 3val:10+5/secval:3+3/secRESETval:0Sum = 13ร—Strategy: Reset Highest Growth Elements FirstOptimal Order:1. Reset element with +5/sec growth rate2. Reset element with +3/sec growth rate3. Reset element with +1/sec growth rateDP Recurrence:dp[i][j] = min( dp[i-1][j] + contribution_at_time_t, dp[i-1][j-1] + reset_contribution)
Understanding the Visualization
1
Initial State
Arrays start with given values, growth rates determine increase per second
2
Growth Phase
All elements increase by their respective growth rates
3
Reset Phase
Choose one element to reset to 0 - prioritize high growth elements
4
Repeat Until Goal
Continue until total sum โ‰ค x
Key Takeaway
๐ŸŽฏ Key Insight: Sort by growth rate and use DP to find optimal reset timing - prioritize resetting high-growth elements early to minimize total accumulation
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
26.0K Views
Medium Frequency
~35 min Avg. Time
847 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