Count minimum number of fountains to be activated to cover the entire garden

There is a one-dimensional garden of length N. In each position of the N length garden, a fountain has been installed. Given an array a[]such that a[i] describes the coverage limit of ith fountain. A fountain can cover the range from the position max(i – a[i], 1) to min(i + a[i], N). In beginning, all the fountains are switched off. The task is to find the minimum number of fountains needed to be activated such that the whole N-length garden can be covered by water.
Examples:
Input: a[] = {1, 2, 1}
Output: 1
Explanation:
For position 1: a[1] = 1, range = 1 to 2
For position 2: a[2] = 2, range = 1 to 3
For position 3: a[3] = 1, range = 2 to 3
Therefore, the fountain at position a[2] covers the whole garden.
Therefore, the required output is 1.Input: a[] = {2, 1, 1, 2, 1}Â
Output: 2Â
Approach: The problem can be solved using Dynamic Programming. Follow the steps below to solve the problem:Â
- traverse the array and for every array index, i.e. ith fountain, find the leftmost fountain up to which the current fountain covers.
- Then, find the rightmost fountain that the leftmost fountain obtained in the above step covers up to and update it in the dp[] array.
- Initialize a variable cntFount to store the minimum number of fountains that need to be activated.
- Now, traverse the dp[] array and keep activating the fountains from the left that covers maximum fountains currently on the right and increment cntFount by 1. Finally, print cntFount as the required answer.
Below is the implementation of the above approach.
C++14
// C++ program to implement// the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find minimum// number of fountains to be// activatedint minCntFoun(int a[], int N){Â
    // dp[i]: Stores the position of    // rightmost fountain that can    // be covered by water of leftmost    // fountain of the i-th fountain    int dp[N];         // initializing all dp[i] values to be -1,     // so that we don't get garbage value      for(int i=0;i<N;i++){          dp[i]=-1;    }Â
    // Stores index of leftmost fountain    // in the range of i-th fountain    int idxLeft;Â
    // Stores index of rightmost fountain    // in the range of i-th fountain    int idxRight;Â
    // Traverse the array    for (int i = 0; i < N; i++) {        idxLeft = max(i - a[i], 0);        idxRight = min(i + (a[i] + 1), N);        dp[idxLeft] = max(dp[idxLeft],                          idxRight);    }Â
    // Stores count of fountains    // needed to be activated    int cntfount = 1;Â
    idxRight = dp[0];Â
    // Stores index of next fountain    // that needed to be activated    // initializing idxNext with -1     // so that we don't get garbage value    int idxNext=-1;Â
    // Traverse dp[] array    for (int i = 0; i < N; i++)     {        idxNext = max(idxNext,                      dp[i]);Â
        // If left most fountain        // cover all its range        if (i == idxRight)         {            cntfount++;            idxRight = idxNext;        }    }Â
    return cntfount;}Â
// Driver Codeint main(){Â Â Â Â int a[] = { 1, 2, 1 };Â Â Â Â int N = sizeof(a) / sizeof(a[0]);Â Â Â Â cout << minCntFoun(a, N);} |
Java
// Java program to implement// the above approachimport java.util.*;Â
class GFG {Â
    // Function to find minimum    // number of fountains to be    // activated    static int minCntFoun(int a[], int N)    {Â
        // dp[i]: Stores the position of        // rightmost fountain that can        // be covered by water of leftmost        // fountain of the i-th fountain        int[] dp = new int[N];        for(int i=0;i<N;i++)        {             dp[i]=-1;        }Â
        // Stores index of leftmost fountain        // in the range of i-th fountain        int idxLeft;Â
        // Stores index of rightmost fountain        // in the range of i-th fountain        int idxRight;Â
        // Traverse the array        for (int i = 0; i < N; i++)         {            idxLeft = Math.max(i - a[i], 0);            idxRight = Math.min(i + (a[i] + 1), N);            dp[idxLeft] = Math.max(dp[idxLeft],                                    idxRight);        }Â
        // Stores count of fountains        // needed to be activated        int cntfount = 1;Â
        // Stores index of next fountain        // that needed to be activated        int idxNext = 0;        idxRight = dp[0];Â
        // Traverse dp[] array        for (int i = 0; i < N; i++)        {            idxNext = Math.max(idxNext, dp[i]);Â
            // If left most fountain            // cover all its range            if (i == idxRight)             {                cntfount++;                idxRight = idxNext;            }        }        return cntfount;    }Â
    // Driver Code    public static void main(String[] args)    {        int a[] = { 1, 2, 1 };        int N = a.length;Â
        System.out.print(minCntFoun(a, N));    }}Â
// This code is contributed by Amit Katiyar |
Python3
# Python3 program to implement# the above approachÂ
# Function to find minimum# number of fountains to be# activatedÂ
Â
def minCntFoun(a, N):Â
    # dp[i]: Stores the position of    # rightmost fountain that can    # be covered by water of leftmost    # fountain of the i-th fountain    dp = [0] * N    for i in range(N):      dp[i] = -1Â
    # Traverse the array    for i in range(N):        idxLeft = max(i - a[i], 0)        idxRight = min(i + (a[i] + 1), N)        dp[idxLeft] = max(dp[idxLeft],                          idxRight)Â
    # Stores count of fountains    # needed to be activated    cntfount = 1Â
    idxRight = dp[0]Â
    # Stores index of next fountain    # that needed to be activated    idxNext = 0Â
    # Traverse dp[] array    for i in range(N):        idxNext = max(idxNext,                      dp[i])Â
        # If left most fountain        # cover all its range        if (i == idxRight):            cntfount += 1            idxRight = idxNextÂ
    return cntfountÂ
Â
# Driver codeif __name__ == '__main__':Â
    a = [1, 2, 1]    N = len(a)Â
    print(minCntFoun(a, N))Â
# This code is contributed by Shivam Singh |
C#
// C# program to implement// the above approachusing System;class GFG {Â
    // Function to find minimum    // number of fountains to be    // activated    static int minCntFoun(int[] a, int N)    {        // dp[i]: Stores the position of        // rightmost fountain that can        // be covered by water of leftmost        // fountain of the i-th fountain        int[] dp = new int[N];        for (int i = 0; i < N; i++)         {            dp[i] = -1;        }Â
        // Stores index of leftmost        // fountain in the range of        // i-th fountain        int idxLeft;Â
        // Stores index of rightmost        // fountain in the range of        // i-th fountain        int idxRight;Â
        // Traverse the array        for (int i = 0; i < N; i++) {            idxLeft = Math.Max(i - a[i], 0);            idxRight = Math.Min(i + (a[i] + 1),                                 N);            dp[idxLeft] = Math.Max(dp[idxLeft],                                    idxRight);        }Â
        // Stores count of fountains        // needed to be activated        int cntfount = 1;Â
        // Stores index of next        // fountain that needed        // to be activated        int idxNext = 0;        idxRight = dp[0];Â
        // Traverse []dp array        for (int i = 0; i < N; i++)         {            idxNext = Math.Max(idxNext, dp[i]);Â
            // If left most fountain            // cover all its range            if (i == idxRight)             {                cntfount++;                idxRight = idxNext;            }        }        return cntfount;    }Â
    // Driver Code    public static void Main(String[] args)    {        int[] a = { 1, 2, 1 };        int N = a.Length;Â
        Console.Write(minCntFoun(a, N));    }}Â
// This code is contributed by gauravrajput1 |
Javascript
<script>Â
// Javascript program to implement// the above approachÂ
// Function to find minimum// number of fountains to be// activatedfunction minCntFoun(a, N){         // dp[i]: Stores the position of    // rightmost fountain that can    // be covered by water of leftmost    // fountain of the i-th fountain    let dp = [];    for(let i = 0; i < N; i++)    {         dp[i] = -1;    }Â
    // Stores index of leftmost fountain    // in the range of i-th fountain    let idxLeft;Â
    // Stores index of rightmost fountain    // in the range of i-th fountain    let idxRight;Â
    // Traverse the array    for(let i = 0; i < N; i++)    {        idxLeft = Math.max(i - a[i], 0);        idxRight = Math.min(i + (a[i] + 1), N);        dp[idxLeft] = Math.max(dp[idxLeft],                               idxRight);    }Â
    // Stores count of fountains    // needed to be activated    let cntfount = 1;Â
    // Stores index of next fountain    // that needed to be activated    let idxNext = 0;    idxRight = dp[0];Â
    // Traverse dp[] array    for(let i = 0; i < N; i++)    {        idxNext = Math.max(idxNext, dp[i]);Â
        // If left most fountain        // cover all its range        if (i == idxRight)        {            cntfount++;            idxRight = idxNext;        }    }    return cntfount;}Â
// Driver Codelet a = [ 1, 2, 1 ];let N = a.length;Â
document.write(minCntFoun(a, N));Â
// This code is contributed by souravghosh0416Â
</script> |
Â
Â
1
Â
Time Complexity: O(N)
Auxiliary Space: O(N)
 Brute Force in python:
Approach:
The brute force approach involves checking all possible combinations of fountains that can be activated to cover the entire garden. For each combination, we check if it covers the entire garden and keep track of the minimum number of fountains required.
Initialize the minimum number of fountains to a very large number.
Use a loop to iterate over all possible combinations of fountains that can be activated.
For each combination, check if it covers the entire garden using a helper function is_covered.
If it does, update the minimum number of fountains required.
Return the minimum number of fountains required.
Python3
def activate_fountains(fountains):Â Â Â Â n = len(fountains)Â Â Â Â min_fountains = float('inf')Â Â Â Â for i in range(1, 2**n):Â Â Â Â Â Â Â Â activated = []Â Â Â Â Â Â Â Â for j in range(n):Â Â Â Â Â Â Â Â Â Â Â Â if (i >> j) & 1:Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â activated.append(j)Â Â Â Â Â Â Â Â if is_covered(activated, fountains):Â Â Â Â Â Â Â Â Â Â Â Â min_fountains = min(min_fountains, len(activated))Â Â Â Â return min_fountainsÂ
def is_covered(activated, fountains):    n = len(fountains)    coverage = [0] * n    for i in activated:        left = max(0, i - fountains[i])        right = min(n - 1, i + fountains[i])        for j in range(left, right + 1):            coverage[j] = 1    return all(coverage)Â
# example usagea1 = [1, 2, 1]a2 = [2, 1, 1, 2, 1]print(activate_fountains(a1)) # output: 1print(activate_fountains(a2)) # output: 2 |
1 2
The time complexity of this approach is O(2^n) where n is the number of fountainsÂ
 the space complexity is O(n).
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



