Given two integers X and Y and a binary array arr[] of length N whose first and last element is 1, the task is to minimize the cost to convert all array elements to 0, where X and Y represent the cost of converting a subarray of all 1s to 0s and the cost of converting any element to 0 respectively.
Examples:
Input: arr[] = {1, 1, 1, 0, 1, 1}, X = 10, Y = 4
Output: 14
Explanation: To minimize the cost to convert all elements to 0, perform the following operations:Â
- Change element at index 3 to 1. Now the array modifies to {1, 1, 1, 1, 1, 1}. The cost of this operation is 4.
- Change all element of the array to 0. The cost of this operation is 10.
Therefore, the total cost is 4 + 10 + 14.Input: arr[] = {1, 0, 0, 1, 1, 0, 1}, X = 2, Y = 3
Output: 6
Explanation: To minimize the cost of changing all array elements to 0, perform the following operations:Â
- Change all element of the subarray over the range [3, 4] to 0. Now the array modifies to {1, 0, 0, 0, 0, 0, 1}. The cost of this operation is 2.
- Change all element of the subarray over the range [0, 0] to 0. Now the array modifies to {0, 0, 0, 0, 0, 0, 1}. The cost of this operation is 2.
- Change all element of the subarray over the range [6, 6] to 0. Now the array modifies to {0, 0, 0, 0, 0, 0, 0}. The cost of this operation is 2.
Therefore, the total cost is 2 + 2 + 2 = 3.
Approach: Follow the steps:
- Initialize a variable, say ans, to store the minimum cost of converting all array elements to 0.
- Calculate and store the lengths of all subarrays consisting of 0s only and store it in a vector and sort the vector in increasing order.
- Now, count the number of subarrays consisting of 1s only.
- Traverse the given array using the variable i, where i represents number of Y cost operations, and perform the following:
- For every possible number of operations of cost Y, find the cost by performing X operations.
- Since, on setting bits in between two groups of 1s, the total number of groups gets decreased, first merge the two groups of consecutive 1s to reduce the minimum number of operations.
- Find the minimum cost of completing the above step for each index as currCost and update ans to store the minimum of ans and currCost.
- After completing the above steps, print the value of ans as the minimum cost.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to calculate the minimum cost // of converting all array elements to 0s void minimumCost( int * binary, int n,                  int a, int b) {     // Stores subarrays of 0s only     vector< int > groupOfZeros; Â
    int len = 0, i = 0;     bool increment_need = true ; Â
    // Traverse the array     while (i < n) {         increment_need = true ; Â
        // If consecutive 0s occur         while (i < n && binary[i] == 0) {             len++;             i++;             increment_need = false ;         } Â
        // Increment if needed         if (increment_need == true ) {             i++;         } Â
        // Push the current length of         // consecutive 0s in a vector         if (len != 0) {             groupOfZeros.push_back(len);         } Â
        // Update lengths as 0         len = 0;     } Â
    // Sorting vector     sort(groupOfZeros.begin(),          groupOfZeros.end()); Â
    i = 0;     bool found_ones = false ; Â
    // Stores the number of     // subarrays consisting of 1s     int NumOfOnes = 0; Â
    // Traverse the array     while (i < n) {         found_ones = false ; Â
        // If current element is 1         while (i < n && binary[i] == 1) {             i++;             found_ones = true ;         }         if (found_ones == false )             i++; Â
        // Otherwise         else Â
            // Increment count of             // consecutive ones             NumOfOnes++;     } Â
    // Stores the minimum cost     int ans = INT_MAX; Â
    // Traverse the array     for ( int i = 0; i < n; i++) { Â
        int curr = 0, totalOnes = NumOfOnes; Â
        // First element         if (i == 0) {             curr = totalOnes * a;         }         else { Â
            int mark = i, num_of_changes = 0; Â
            // Traverse the subarray sizes             for ( int x : groupOfZeros) { Â
                if (mark >= x) {                     totalOnes--;                     mark -= x; Â
                    // Update cost                     num_of_changes += x;                 }                 else {                     break ;                 }             } Â
            // Cost of performing X             // and Y operations             curr = (num_of_changes * b)                    + (totalOnes * a);         } Â
        // Find the minimum cost         ans = min(ans, curr);     } Â
    // Print the minimum cost     cout << ans; } Â
// Driver Code int main() { Â Â Â Â int arr[] = { 1, 1, 1, 0, 1, 1 }; Â Â Â Â int N = sizeof (arr) / sizeof (arr[0]); Â Â Â Â int X = 10, Y = 4; Â
    // Function Call     minimumCost(arr, N, X, Y); Â
    return 0; } |
Java
// Java program for the above approach import java.io.*; import java.util.*; Â
class GFG{ Â
// Function to calculate the minimum cost // of converting all array elements to 0s public static void minimumCost( int [] binary, int n,                                int a, int b) {          // Stores subarrays of 0s only     List<Integer> groupOfZeros = new ArrayList<Integer>(); Â
    int len = 0 , i = 0 ;     boolean increment_need = true ; Â
    // Traverse the array     while (i < n)     {         increment_need = true ; Â
        // If consecutive 0s occur         while (i < n && binary[i] == 0 )         {             len++;             i++;             increment_need = false ;         } Â
        // Increment if needed         if (increment_need == true )         {             i++;         } Â
        // Push the current length of         // consecutive 0s in a vector         if (len != 0 )         {             groupOfZeros.add(len);         } Â
        // Update lengths as 0         len = 0 ;     } Â
    // Sorting List     Collections.sort(groupOfZeros); Â
    i = 0 ;     boolean found_ones = false ; Â
    // Stores the number of     // subarrays consisting of 1s     int NumOfOnes = 0 ; Â
    // Traverse the array     while (i < n)     {         found_ones = false ; Â
        // If current element is 1         while (i < n && binary[i] == 1 )         {             i++;             found_ones = true ;         }         if (found_ones == false )             i++; Â
        // Otherwise         else Â
            // Increment count of             // consecutive ones             NumOfOnes++;     } Â
    // Stores the minimum cost     int ans = Integer.MAX_VALUE; Â
    // Traverse the array     for ( int i1 = 0 ; i1 < n; i1++)     {         int curr = 0 , totalOnes = NumOfOnes; Â
        // First element         if (i1 == 0 )         {             curr = totalOnes * a;         }         else         {             int mark = i1, num_of_changes = 0 ; Â
            // Traverse the subarray sizes             for ( int x : groupOfZeros)             {                 if (mark >= x)                 {                     totalOnes--;                     mark -= x;                                          // Update cost                     num_of_changes += x;                 }                 else                 {                     break ;                 }             } Â
            // Cost of performing X             // and Y operations             curr = (num_of_changes * b) +                         (totalOnes * a);         } Â
        // Find the minimum cost         ans = Math.min(ans, curr);     } Â
    // Print the minimum cost     System.out.println(ans); } Â
// Driver code public static void main(String[] args) {     int arr[] = { 1 , 1 , 1 , 0 , 1 , 1 };     int N = 6 ;     int X = 10 , Y = 4 ;          // Function Call     minimumCost(arr, N, X, Y); } } Â
// This code is contributed by RohitOberoi |
Python3
# Python3 program for the above approach import sys Â
# Function to calculate the minimum cost # of converting all array elements to 0s def minimumCost(binary, n,                 a, b): Â
    # Stores subarrays of 0s only     groupOfZeros = [] Â
    length = 0     i = 0     increment_need = True Â
    # Traverse the array     while (i < n):         increment_need = True Â
        # If consecutive 0s occur         while (i < n and binary[i] = = 0 ):             length + = 1             i + = 1             increment_need = False Â
        # Increment if needed         if (increment_need = = True ):             i + = 1 Â
        # Push the current length of         # consecutive 0s in a vector         if (length ! = 0 ):             groupOfZeros.append(length) Â
        # Update lengths as 0         length = 0 Â
    # Sorting vector     groupOfZeros.sort() Â
    i = 0     found_ones = False Â
    # Stores the number of     # subarrays consisting of 1s     NumOfOnes = 0 Â
    # Traverse the array     while (i < n):         found_ones = False Â
        # If current element is 1         while (i < n and binary[i] = = 1 ):             i + = 1             found_ones = True Â
        if (found_ones = = False ):             i + = 1 Â
        # Otherwise         else : Â
            # Increment count of             # consecutive ones             NumOfOnes + = 1 Â
    # Stores the minimum cost     ans = sys.maxsize Â
    # Traverse the array     for i in range (n): Â
        curr = 0         totalOnes = NumOfOnes Â
        # First element         if (i = = 0 ):             curr = totalOnes * a Â
        else : Â
            mark = i             num_of_changes = 0 Â
            # Traverse the subarray sizes             for x in groupOfZeros: Â
                if (mark > = x):                     totalOnes - = 1                     mark - = x Â
                    # Update cost                     num_of_changes + = x Â
                else :                     break Â
            # Cost of performing X             # and Y operations             curr = ((num_of_changes * b)                     + (totalOnes * a)) Â
        # Find the minimum cost         ans = min (ans, curr) Â
    # Print the minimum cost     print (ans) Â
# Driver Code if __name__ = = "__main__" : Â Â Â Â arr = [ 1 , 1 , 1 , 0 , 1 , 1 ] Â Â Â Â N = len (arr) Â Â Â Â X = 10 Â Â Â Â Y = 4 Â
    # Function Call     minimumCost(arr, N, X, Y) Â
    # This code is contributed by chitranayal |
C#
// C# program for the above approach using System; using System.Collections.Generic; Â
class GFG{ Â
// Function to calculate the minimum cost // of converting all array elements to 0s public static void minimumCost( int [] binary, int n,                                int a, int b) {        // Stores subarrays of 0s only     List< int > groupOfZeros = new List< int >(); Â
    int len = 0, i = 0;     bool increment_need = true ; Â
    // Traverse the array     while (i < n)     {         increment_need = true ; Â
        // If consecutive 0s occur         while (i < n && binary[i] == 0)         {             len++;             i++;             increment_need = false ;         } Â
        // Increment if needed         if (increment_need == true )         {             i++;         } Â
        // Push the current length of         // consecutive 0s in a vector         if (len != 0)         {             groupOfZeros.Add(len);         } Â
        // Update lengths as 0         len = 0;     } Â
    // Sorting List     groupOfZeros.Sort(); Â
    i = 0;     bool found_ones = false ; Â
    // Stores the number of     // subarrays consisting of 1s     int NumOfOnes = 0; Â
    // Traverse the array     while (i < n)     {         found_ones = false ; Â
        // If current element is 1         while (i < n && binary[i] == 1)         {             i++;             found_ones = true ;         }         if (found_ones == false )             i++; Â
        // Otherwise         else Â
            // Increment count of             // consecutive ones             NumOfOnes++;     } Â
    // Stores the minimum cost     int ans = int .MaxValue; Â
    // Traverse the array     for ( int i1 = 0; i1 < n; i1++)     {         int curr = 0, totalOnes = NumOfOnes; Â
        // First element         if (i1 == 0)         {             curr = totalOnes * a;         }         else         {             int mark = i1, num_of_changes = 0; Â
            // Traverse the subarray sizes             foreach ( int x in groupOfZeros)             {                 if (mark >= x)                 {                     totalOnes--;                     mark -= x;                                          // Update cost                     num_of_changes += x;                 }                 else                 {                     break ;                 }             } Â
            // Cost of performing X             // and Y operations             curr = (num_of_changes * b) +                         (totalOnes * a);         } Â
        // Find the minimum cost         ans = Math.Min(ans, curr);     } Â
    // Print the minimum cost     Console.WriteLine(ans); } Â
// Driver code public static void Main(String[] args) {     int []arr = { 1, 1, 1, 0, 1, 1 };     int N = 6;     int X = 10, Y = 4;          // Function Call     minimumCost(arr, N, X, Y); } } Â
// This code is contributed by Amit Katiyar |
Javascript
<script> Â
// JavaScript program for the above approach Â
// Function to calculate the minimum cost // of converting all array elements to 0s function minimumCost(binary, n, a, b) {     // Stores subarrays of 0s only     var groupOfZeros = []; Â
    var len = 0, i = 0;     var increment_need = true ; Â
    // Traverse the array     while (i < n) {         increment_need = true ; Â
        // If consecutive 0s occur         while (i < n && binary[i] == 0) {             len++;             i++;             increment_need = false ;         } Â
        // Increment if needed         if (increment_need == true ) {             i++;         } Â
        // Push the current length of         // consecutive 0s in a vector         if (len != 0) {             groupOfZeros.push(len);         } Â
        // Update lengths as 0         len = 0;     } Â
    // Sorting vector     groupOfZeros.sort((a,b)=>a-b); Â
    i = 0;     var found_ones = false ; Â
    // Stores the number of     // subarrays consisting of 1s     var NumOfOnes = 0; Â
    // Traverse the array     while (i < n) {         found_ones = false ; Â
        // If current element is 1         while (i < n && binary[i] == 1) {             i++;             found_ones = true ;         }         if (found_ones == false )             i++; Â
        // Otherwise         else Â
            // Increment count of             // consecutive ones             NumOfOnes++;     } Â
    // Stores the minimum cost     var ans = 1000000000; Â
    // Traverse the array     for ( var i = 0; i < n; i++) { Â
        var curr = 0, totalOnes = NumOfOnes; Â
        // First element         if (i == 0) {             curr = totalOnes * a;         }         else { Â
            var mark = i, num_of_changes = 0; Â
            // Traverse the subarray sizes             groupOfZeros.forEach(x => {                  Â
                if (mark >= x) {                     totalOnes--;                     mark -= x; Â
                    // Update cost                     num_of_changes += x;                 }                              }); Â
            // Cost of performing X             // and Y operations             curr = (num_of_changes * b)                    + (totalOnes * a);         } Â
        // Find the minimum cost         ans = Math.min(ans, curr);     } Â
    // Print the minimum cost     document.write( ans); } Â
// Driver Code Â
var arr = [ 1, 1, 1, 0, 1, 1 ]; var N = arr.length; var X = 10, Y = 4; Â
// Function Call minimumCost(arr, N, X, Y); Â
Â
</script> |
14
Â
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!