Patching Array in C++


Suppose we have an array nums and one number. We can add elements in the array, such that any number in range [1, n] (both are inclusive) can be formed by the sum of some elements in the array. We have to find the minimum number of required patches. So when the array is like [1,4] and given number is n = 7, then output will be 1, as initially the nums are [1], [4] and [1,4] = 5, now if we add 2 into array, then the nums will be [1], [2], [4], [1,2], [1,4],[2,4], [1,2,4], so the sum values will be 1, 2, 4, 3, 5, 6, 7 respectively.

To solve this, we will follow these steps −

  • req := 1, i := 0, ret := 0

  • while req <= n, do −

    • if i < size of nums and nums[i] <= req, then,

      • req = req + nums[i]

      • increase i by 1

    • Otherwise

      • req = req + req

      • increase ret by 1

  • return ret

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minPatches(vector<int>& nums, int n) {
      long long int req = 1;
      int i = 0;
      int ret = 0;
      while(req <= n){
         if(i < nums.size() && nums[i] <= req){
            req += nums[i];
            i++;
         } else {
            req += req;
            ret++;
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,4};
   cout << (ob.minPatches(v, 7));
}

Input

{1,4}

Output

1

Updated on: 27-May-2020

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements