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

What is GEEK

Buddha Community

Minimum Decrements on Subarrays required to reduce all Array elements to zero
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

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

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

Minimize count of increments of each element of subarrays required to make Array

Given an array arr[] consisting of N integers, the task is to find the minimum number of operations, which involves incrementing all elements of a subarray by 1, required to make the array non-increasing.

Examples:

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

Output:_ 4 _

Explanation:

_In operation 1: Choose the subarray {1} and increase its value by 1. Now arr[] = {2, 3, 4, 1, 2} _

_In operation 2: Choose the subarray {2} and increase its value by 1. Now arr[] = {3, 3, 4, 1, 2} _

_In operation 3: Choose the subarray {3, 3} and increase its value by 1. Now arr[] = {4, 4, 4, 1, 2} _

_In operation 4: Choose the subarray {1} and increase its value by 1. Now arr[] = {4, 4, 4, 2, 2} _

Thus, it took 4 operations to make the array non-increasing.

Input:_ arr[] = {10, 9, 8, 7, 7} _

Output:_ 0 _

Explanation:

The array is already non-increasing

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

Approach: The approach is based on the fact that the operations can only be performed on subarrays. So only check for contiguous elements. Below are the steps:

  1. Otherwise, initialize a variable, say res, to store the count of operations required.
  2. Now, traverse the array and for each element, check if the element at index i is smaller than the element at index (i + 1). If found to be true, then add the difference between them to res, since both the elements need to be made equal to make the array non-increasing.
  3. Otherwise, move to the next element and repeat the above steps.
  4. Finally, after complete the traversal of the array, print the final value of res.

Below is the implementation of the above approach:

  • Java
  • Python3
  • C#

// Java program for the above approach

**import** java.io.*;

**import** java.util.*;

**class** GFG {

// Function to find the minimum

// number of operations required to

// make the array non-increasing

**public** **static** **int** getMinOps(``**int**``[] arr)

{

// Stores the count of

// required operations

**int** res = 0``;

**for** (``**int** i = 0``;

i < arr.length - 1``; i++) 

{

// If arr[i] > arr[i+1],

// no increments required.

// Otherwise, add their

// difference to the answer

res += Math.max(arr[i + 1``]

- arr[i],

0``);

}

// Return the result res

**return** res;

}

// Driver Code

**public** **static** **void** main(String[] args)

{

**int**``[] arr = { 1``, 3``, 4``, 1``, 2 };

System.out.println(getMinOps(arr));

}

}

Output:

4

Time Complexity:_ O(N) _

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 #subarray