Houston  Sipes

Houston Sipes

1598022000

Minimum Subarray flips required to convert all elements of a Binary Array to K

Given an array of integers arr[] and a binary string str of length N, the task is to rearrange given array by swapping array elements from indices having the same character in the string, such that the number formed by the elements of the rearranged array as digits is the maximum possible.

Examples:

Input:_ arr[]={1, 3, 4, 2}, str=”0101”_

Output:_ 4 3 1 2_

Explanation:

Since arr[0] is less than arr[2], so swap them. Therefore the maximum possible number from the array is 4, 3, 1, 2.

Input:_ arr[] = { 1, 3, 456, 6, 7, 8 }, str = “101101”_

Output:_ 8 7 6 456 3 1_

Explanation:

Array elements present at 0-chractered indices: {3, 7}

Largest number that can be formed from the above two numbers is 73

Array elements present at 1-chractered indices: {1, 456, 6, 8}

Largest number that can be formed from the above two numbers is 864561

Therefore, maximum number that can be generated from the array is 87645631

Approach: Follow the steps below to solve the problem:

  1. Create two arrays to store 0-charactered index elements and 1-charactered index elements from the array.
  2. Sort the arrays to form largest possible numbers from these two arrays.
  3. Iterate over str and based on the characters, place array elements from the sorted arrays.

Below is the implementation of the above approach:

  • C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Comparison Function to sort()

**int** myCompare(``**int** a, **int** b)

{

string X = to_string(a);

string Y = to_string(b);

// Append Y at the end of X

string XY = X.append(Y);

// Append X at the end of Y

string YX = Y.append(X);

// Compare and return greater

**return** XY.compare(YX) < 0 ? 1 : 0;

}

// Function to return the rearranged

// array in the form of largest

// possible number that can be formed

**void** findMaxArray(vector<``**int**``>& arr, string& str)

{

**int** N = arr.size();

vector<``**int**``> Z, O, ans(N);

**for** (``**int** i = 0; i < N; i++) {

**if** (str[i] == '0'``) {

Z.push_back(arr[i]);

}

**else** {

O.push_back(arr[i]);

}

}

// Sort them in decreasing order

sort(Z.rbegin(), Z.rend(), myCompare);

sort(O.rbegin(), O.rend(), myCompare);

**int** j = 0, k = 0;

// Generate the sorted array

**for** (``**int** i = 0; i < N; i++) {

**if** (str[i] == '0'``) {

ans[i] = Z[j++];

}

**else** {

ans[i] = O[k++];

}

}

**for** (``**int** i = 0; i < N; i++) {

cout << ans[i] << " "``;

}

}

// Driver Code

**int** main()

{

vector<``**int**``> arr = { 1, 3, 456, 6, 7, 8 };

string str = "101101"``;

findMaxArray(arr, str);

**return** 0;

}

Output:

8 7 6 456 3 1

Time Complexity:_ O(NlogN)_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #searching #array-rearrange

What is GEEK

Buddha Community

Minimum Subarray flips required to convert all elements of a Binary Array to K
Houston  Sipes

Houston Sipes

1598022000

Minimum Subarray flips required to convert all elements of a Binary Array to K

Given an array of integers arr[] and a binary string str of length N, the task is to rearrange given array by swapping array elements from indices having the same character in the string, such that the number formed by the elements of the rearranged array as digits is the maximum possible.

Examples:

Input:_ arr[]={1, 3, 4, 2}, str=”0101”_

Output:_ 4 3 1 2_

Explanation:

Since arr[0] is less than arr[2], so swap them. Therefore the maximum possible number from the array is 4, 3, 1, 2.

Input:_ arr[] = { 1, 3, 456, 6, 7, 8 }, str = “101101”_

Output:_ 8 7 6 456 3 1_

Explanation:

Array elements present at 0-chractered indices: {3, 7}

Largest number that can be formed from the above two numbers is 73

Array elements present at 1-chractered indices: {1, 456, 6, 8}

Largest number that can be formed from the above two numbers is 864561

Therefore, maximum number that can be generated from the array is 87645631

Approach: Follow the steps below to solve the problem:

  1. Create two arrays to store 0-charactered index elements and 1-charactered index elements from the array.
  2. Sort the arrays to form largest possible numbers from these two arrays.
  3. Iterate over str and based on the characters, place array elements from the sorted arrays.

Below is the implementation of the above approach:

  • C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Comparison Function to sort()

**int** myCompare(``**int** a, **int** b)

{

string X = to_string(a);

string Y = to_string(b);

// Append Y at the end of X

string XY = X.append(Y);

// Append X at the end of Y

string YX = Y.append(X);

// Compare and return greater

**return** XY.compare(YX) < 0 ? 1 : 0;

}

// Function to return the rearranged

// array in the form of largest

// possible number that can be formed

**void** findMaxArray(vector<``**int**``>& arr, string& str)

{

**int** N = arr.size();

vector<``**int**``> Z, O, ans(N);

**for** (``**int** i = 0; i < N; i++) {

**if** (str[i] == '0'``) {

Z.push_back(arr[i]);

}

**else** {

O.push_back(arr[i]);

}

}

// Sort them in decreasing order

sort(Z.rbegin(), Z.rend(), myCompare);

sort(O.rbegin(), O.rend(), myCompare);

**int** j = 0, k = 0;

// Generate the sorted array

**for** (``**int** i = 0; i < N; i++) {

**if** (str[i] == '0'``) {

ans[i] = Z[j++];

}

**else** {

ans[i] = O[k++];

}

}

**for** (``**int** i = 0; i < N; i++) {

cout << ans[i] << " "``;

}

}

// Driver Code

**int** main()

{

vector<``**int**``> arr = { 1, 3, 456, 6, 7, 8 };

string str = "101101"``;

findMaxArray(arr, str);

**return** 0;

}

Output:

8 7 6 456 3 1

Time Complexity:_ O(NlogN)_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #searching #array-rearrange

Alayna  Rippin

Alayna Rippin

1597014000

Minimum cost required to convert all Subarrays of size K to a single element

Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum cost required to make each element of every subarray of length K equal. Cost of replacing any array element by another element is the absolute difference between the two.

Examples:

Input: A[] = {1, 2, 3, 4, 6}, K = 3
Output: 7
Explanation:
Subarray 1: Cost to convert subarray {1, 2, 3} to {2, 2, 2} = |1-2| + |2-2| + |3-2| = 2
Subarray 2: Cost to convert subarray {2, 3, 4} to {3, 3, 3} = |2-3| + |3-3| + |4-3| = 2
Subarray 3: Cost to convert subarray {3, 4, 6} to {4, 4, 4} = |3-4| + |4-4| + |6-4| = 3
Minimum Cost = 2 + 2 + 3 = 7/
Input: A[] = {2, 3, 4, 4, 1, 7, 6}, K = 4
Output: 21

Approach:

To find the minimum cost to convert each element of the subarray to a single element, change every element of the subarray to the median of that subarray. Follow the steps below to solve the problem:

To find the median for each running subarray efficiently, use a multiset to get the sorted order of elements in each subarray. Median will be the middle element of this multiset.
For the next subarray remove the leftmost element of the previous subarray from the multiset, add the current element to the multiset.
Keep a pointer mid to efficiently keep track of the middle element of the multiset.
If the newly added element is smaller than the previous middle element, move mid to its immediate smaller element. Otherwise, move mid to its immediate next element.
Calaculate cost of replacing every element of the subarray by the equation | A[i] – medianeach_subarray |.
Finally print the total cost.
Below is the implementation for the above approach:

C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

using namespace std;

// Function to find the minimum

// cost to convert each element of

// every subarray of size K equal

int minimumCost(vector arr, int n,

            int k) 

{

// Stores the minimum cost 

int totalcost = 0; 

int i, j; 



// Stores the first K elements 

multiset<int> mp(arr.begin(), 

                 arr.begin() + k); 



if (k == n) { 



    // Obtain the middle element of 

    // the multiset 

    auto mid = next(mp.begin(), 

                    n / 2 - ((k + 1) % 2)); 



    int z = *mid; 



    // Calculate cost for the subarray 

    for (i = 0; i < n; i++) 

        totalcost += abs(z - arr[i]); 



    // Return the total cost 

    return totalcost; 

} 

else { 



    // Obtain the middle element 

    // in multiset 

    auto mid = next(mp.begin(), 

                    k / 2 - ((k + 1) % 2)); 



    for (i = k; i < n; i++) { 



        int zz = *mid; 

        int cost = 0; 

        for (j = i - k; j < i; j++) { 



            // Cost for the previous 

            // k length subarray 

            cost += abs(arr[j] - zz); 

        } 

        totalcost += cost; 



        // Insert current element 

        // into multiset 

        mp.insert(arr[i]); 



        if (arr[i] < *mid) { 



            // New element appears 

            // to the left of mid 

            mid--; 

        } 



        if (arr[i - k] <= *mid) { 



            // New element appears 

            // to the right of mid 

            mid++; 

        } 



        // Remove leftmost element 

        // from the window 

        mp.erase(mp.lower_bound(arr[i - k])); 



        // For last element 

        if (i == n - 1) { 

            zz = *mid; 

            cost = 0; 



            for (j = i - k + 1; 

                 j <= i; j++) { 



                // Calculate cost for the subarray 

                cost += abs(zz - arr[j]); 

            } 



            totalcost += cost; 

        } 

    } 



    // Return the total cost 

    return totalcost; 

} 

}

// Driver Code

int main()

{

int N = 5, K = 3; 



vector<int> A({ 1, 2, 3, 4, 6 }); 



cout << minimumCost(A, N, K); 

}

Output:

7

Time Complexity: O(NlogN)

Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #sorting #cpp-multiset #median-finding #sliding-window #subarray

Mitchel  Carter

Mitchel Carter

1597784400

Minimum Decrements on Subarrays required to reduce all Array elements to zero

Given an array **arr[] **consisting of N non-negative integers, the task is to find the minimum number of subarrays that needs to be reduced by 1 such that all the array elements are equal to 0.

Example:

_Input: _arr[] = {1, 2, 3, 2, 1}

_Output: _3

Explanation:

Operation 1: {1, 2, 3, 2, 1} -> {0, 1, 2, 1, 0}

Operation 2: {0, 1, 2, 1, 0} -> {0, 0, 1, 0, 0}

Operation 3: {0, 0, 1, 0, 0} -> {0, 0, 0, 0, 0}

_Input: _arr[] = {5, 4, 3, 4, 4}

_Output: _6

Explanation:

{5, 4, 3, 4, 4} -> {4, 3, 2, 3, 3} -> {3, 2, 1, 2, 2} -> {2, 1, 0, 1, 1} -> {2, 1, 0, 0, 0} -> {1, 0, 0, 0, 0} -> {0, 0, 0, 0, 0}

Approach:

This can be optimally done by traversing the given array from index 0, finding the answer up to index i, where 0 ≤ i < N. If arr[i] ≥ arr[i+1], then (i + 1)th element can eb included in every subarray operation of ith element, thus requiring no extra operations. If arr[i] < arr[i + 1], then (i + 1)th element can be included in every subarray operation of ith element and after all operations, arr[i+1] becomes arr[i+1]-arr[i]. Therefore, we need arr[i+1]-arr[i] extra operations to reduce it zero.

Follow the below steps to solve the problem:

  • Add the first element arr[0] to **answer **as we need at least **arr[0] **to make the given array 0.

  • Traverse over indices [1, N-1] and for every element, check if it is greater than the previous element. If found to be true, add their difference to the answer.

  • Below is the implementation of above approach:

  • C++

  • Java

  • Python

  • // C++ Program to implement

  • // the above approach

  • #include <bits/stdc++.h>

  • **using** **namespace** std;

  • // Function to count the minimum

  • // number of subarrays that are

  • // required to be decremented by 1

  • **int** min_operations(vector<``**int**``>& A)

  • {

  • // Base Case

  • **if** (A.size() == 0)

  • **return** 0;

  • // Initialize ans to first element

  • **int** ans = A[0];

  • **for** (``**int** i = 1; i < A.size(); i++) {

  • // For A[i] > A[i-1], operation

  • // (A[i] - A[i - 1]) is required

  • ans += max(A[i] - A[i - 1], 0);

  • }

  • // Return the answer

  • **return** ans;

  • }

  • // Driver Code

  • **int** main()

  • {

  • vector<``**int**``> A{ 1, 2, 3, 2, 1 };

  • cout << min_operations(A) << "\n"``;

  • **return** 0;

  • }

  • Output:

3
  • Time Complexity:_ O(N)_
  • Auxiliary Space:_ O(N)_
  • Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #searching #subarray

Find array elements equal to sum of any subarray of at least size 2

Given an array arr[], the task is to find the elements from the array which are equal to the sum of any sub-array of size greater than 1.

Examples:

Input:_ arr[] = {1, 2, 3, 4, 5, 6}_

Output:_ 3, 5, 6_

Explanation:

The elements 3, 5, 6 are equal to sum of subarrays {1, 2},{2, 3} and {1, 2, 3} respectively.

Input:_ arr[] = {5, 6, 10, 1, 3, 4, 8, 16}_

Output:_ 4, 8, 16_

Explanation:

The elements 4, 8, 16 are equal to the sum of subarrays {1, 3}, {1, 3, 4}, {1, 3, 4, 8} respectively

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to use prefix sum array to solve the given problem. Create a prefix[] array that stores the prefix sum of all its preceding elements for every index. Store the sum of all subarrays in a map and search if any array element is present in the map or not.

#arrays #hash #prefix-sum #subarray #subarray-sum

Find array elements equal to sum of any subarray of at least size 2

Given an array arr[], the task is to find the elements from the array which are equal to the sum of any sub-array of size greater than 1.

Examples:

Input:_ arr[] = {1, 2, 3, 4, 5, 6}_

Output:_ 3, 5, 6_

Explanation:

The elements 3, 5, 6 are equal to sum of subarrays {1, 2},{2, 3} and {1, 2, 3} respectively.

Input:_ arr[] = {5, 6, 10, 1, 3, 4, 8, 16}_

Output:_ 4, 8, 16_

Explanation:

The elements 4, 8, 16 are equal to the sum of subarrays {1, 3}, {1, 3, 4}, {1, 3, 4, 8} respectively

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to use prefix sum array to solve the given problem. Create a prefix[] array that stores the prefix sum of all its preceding elements for every index. Store the sum of all subarrays in a map and search if any array element is present in the map or not.

#arrays #hash #prefix-sum #subarray #subarray-sum