Minimum Time to Make Array Sum At Most x - Problem

You are given two 0-indexed integer arrays nums1 and nums2 of equal length. Every second, for all indices 0 <= i < nums1.length, the value of nums1[i] is incremented by nums2[i].

After this increment operation is done, you can perform the following operation:

  • Choose an index 0 <= i < nums1.length and make nums1[i] = 0.

You are also given an integer x.

Return the minimum time in which you can make the sum of all elements of nums1 to be less than or equal to x, or -1 if this is not possible.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,2,3], nums2 = [1,4,2], x = 4
Output: 2
💡 Note: At time 3: We can operate on index 1 (highest growth rate) at time 1, index 2 at time 2, and index 0 at time 3. After simulation, the final sum becomes ≤ 4.
Example 2 — Already Satisfied
$ Input: nums1 = [1,1,1], nums2 = [1,1,1], x = 5
Output: 0
💡 Note: Initial sum is 3 ≤ 5, so no operations needed.
Example 3 — Impossible Case
$ Input: nums1 = [1,2,3], nums2 = [3,3,3], x = 4
Output: -1
💡 Note: Even with optimal operations, we cannot reduce the sum to ≤ 4 due to high growth rates.

Constraints

  • 1 ≤ nums1.length == nums2.length ≤ 1000
  • 1 ≤ nums1[i], nums2[i] ≤ 1000
  • 1 ≤ x ≤ 106

Visualization

Tap to expand
Minimum Time to Make Array Sum At Most x INPUT nums1 (base values) 1 2 3 i=0 i=1 i=2 nums2 (increment rate) 1 4 2 Target: x x = 4 Initial sum(nums1) = 6 sum(nums2) = 7/sec Goal: sum <= 4 ALGORITHM (DP) 1 Sort by nums2 Pairs: (1,1),(3,2),(2,4) 2 Define DP State dp[i][j] = max reduction 3 Transition dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]+nums1[i]+j*nums2[i]) 4 Find minimum t sum - dp[n][t] + t*sum2 <= x DP Table (max savings) t= 0 1 2 3 i=0 0 2 - - i=1 0 5 9 - i=2 0 6 13 23 At t=3: 6+3*7-23 = 4 <= 4 OK FINAL RESULT Time Progression t=0: sum=6 (no reset) t=1: reset i=1, sum=10 t=2: reset i=2, sum=9 t=3: reset i=0, sum=4 Answer 3 sum(nums1) = 4 <= x Goal achieved! OK Optimal: reset indices 1,2,0 Key Insight: Sort pairs by nums2 ascending. When resetting at time t, we save nums1[i] + t*nums2[i]. Higher nums2 values should be reset later (larger t) to maximize savings. DP finds optimal selection. Formula: sum(nums1) + t*sum(nums2) - dp[n][t] <= x. Find minimum t satisfying this. TutorialsPoint - Minimum Time to Make Array Sum At Most x | DP Approach
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
23.1K Views
Medium Frequency
~35 min Avg. Time
890 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