Minimum Number of Taps to Open to Water a Garden in C++

C++Server Side ProgrammingProgramming

Suppose there is a one-dimensional garden on the x-axis. The starting position of the garden is 0, and ending position is n. There are n + 1 taps located at points [0, 1, ..., n] in the garden. If we have an integer n and an integer array ranges of length n + 1 where ranges[i] is the i-th tap can water the area [i - ranges[i], i + ranges[i]] when that area is open.

We have to find the minimum number of taps that should be open to water the whole garden, if there is no possible solution, then return -1.

So, if the input is like n = 5, and ranges = [3,4,1,1,1,0], then the output will be 1, as from the second tap, it will cover the whole ground [-3 to 5].

To solve this, we will follow these steps −

  • To solve this, we will follow these steps −

  • Define an array v of size (n + 1) and fill this with -1

  • for initialize i := 0, when i <= n, update (increase i by 1), do −

    • u := maximum of i - ranges[i] and 0

    • e := minimum of n and i + ranges[i]

    • v[u] := maximum of v[u] and e

  • if v[0] is same as -1, then −

    • return -1

  • curr := v[0]

  • i := 0, next := 0

  • while curr < n, do −

    • while i <= curr, do −

      • next := maximum of next and v[i]

      • (increase i by 1)

    • if next is same as curr, then −

      • return -1

    • curr := next

    • (increase ret by 1)

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minTaps(int n, vector<int>& ranges) {
      int ret = 1;
      vector<int> v(n + 1, -1);
      for (int i = 0; i <= n; i++) {
         int u = max(i - ranges[i], 0);
         int e = min(n, i + ranges[i]);
         v[u] = max(v[u], e);
      }
      if (v[0] == -1)
      return -1;
      int curr = v[0];
      int i = 0;
      int next = 0;
      while (curr < n) {
         while (i <= curr) {
            next = max(next, v[i]);
            i++;
         }
         if (next == curr)
         return -1;
         curr = next;
         ret++;
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {3,4,1,1,1,0};
   cout << (ob.minTaps(5, v));
}

Input

5, {3,4,1,1,1,0}

Output

1
raja
Updated on 08-Jun-2020 11:26:15

Advertisements