Apply Operations to Make Sum of Array Greater Than or Equal to k - Problem

You are given a positive integer k. Initially, you have an array nums = [1].

You can perform any of the following operations on the array any number of times (possibly zero):

  • Choose any element in the array and increase its value by 1.
  • Duplicate any element in the array and add it to the end of the array.

Return the minimum number of operations required to make the sum of elements of the final array greater than or equal to k.

Input & Output

Example 1 — Small Target
$ Input: k = 4
Output: 2
💡 Note: Start with [1]. Duplicate to get [1,1] (1 op). Duplicate again to get [1,1,1,1] with sum=4 (total 2 ops).
Example 2 — Need Increments
$ Input: k = 11
Output: 6
💡 Note: Start with [1]. After 3 duplicates: [1,1,1,1,1,1,1,1] sum=8. Then 3 increments to reach sum=11. Total: 3+3=6 operations.
Example 3 — Already Satisfied
$ Input: k = 1
Output: 0
💡 Note: Initial array [1] already has sum=1 ≥ k=1, so no operations needed.

Constraints

  • 1 ≤ k ≤ 105

Visualization

Tap to expand
Operations to Make Sum >= k INPUT Initial Array: nums = [1] Target Sum: k = 4 Operations: 1. Increase element by 1 2. Duplicate any element Goal: sum(nums) >= 4 ALGORITHM STEPS 1 Start: nums=[1] sum=1, need 4 2 Increment: [1] --> [2] Op #1: sum=2 3 Duplicate: [2] --> [2,2] Op #2: sum=4 4 Check: sum >= k? 4 >= 4: OK! Greedy Strategy: First increment to value x, then duplicate (n-1) times Total ops: (x-1) + (n-1) FINAL RESULT Final Array: 2 2 Sum: 2 + 2 = 4 Output: 2 Verification: Op 1: [1] --> [2] (incr) Op 2: [2] --> [2,2] (dup) sum=4 >= k=4: OK Total: 2 operations Key Insight: For target k, optimal strategy is to increment one element to value x, then duplicate it (n-1) times. Total operations = (x-1) + ceil(k/x) - 1. Minimize by trying x near sqrt(k). Here: x=2 gives 1+1=2 ops. TutorialsPoint - Apply Operations to Make Sum of Array Greater Than or Equal to k | Greedy Strategy
Asked in
Google 15 Meta 12 Amazon 8
8.7K Views
Medium Frequency
~15 min Avg. Time
234 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