Maximize length of Non-Decreasing Subsequence by reversing at most one Subarray

Given a binary array arr[], the task is to find the maximum possible length of non-decreasing subsequence that can be generated by reversing a subarray at most once.

Examples:

Input:_ arr[] = {0, 1, 0, 1}_

_Output: _4

Explanation:

After reversing the subarray from index [2, 3], the array modifies to {0, 0, 1, 1}.

Hence, the longest non-decreasing subsequence is {0, 0, 1, 1}.

Input:_ arr[] = {0, 1, 1, 1, 0, 0, 1, 1, 0}_

_Output: _9

Explanation:

After reversing the subarray from index [2, 6], the array modifies to {0, 0, 0, 1, 1, 1, 1, 1, 0}.

Hence, the longest non-decreasing subsequence is {0, 0, 0, 1, 1, 1, 1, 1}.

Naive Approach: The simplest approach to solve the problem is to reverse each possible subarray in the given array, and find the longest non-decreasing subsequence possible from the array after reversing the subarray.

Time Complexity:_ O(N3)_

Auxiliary Space:_ O(N)_

Efficient Approach: The idea is to use Dynamic Programming to solve the problem. Follow the steps below:

  • Since the array is a binary array the idea is to find the longest subsequence among the subsequences of the forms {0….0}{0…1…}{0…1…0…}, 0…1…0…1.
  • Initialize a dynamic programming table as dp[][] which stores the following:

dp[i][0] : Stores the length of the longest subsequence (0…) from a[0 to i].

dp[i][1] : Stores the length of the longest subsequence (0…1…) from a[0 to i].

dp[i][2] : Stores the length of the longest subsequence (0…1…0…) from a[0 to i].

dp[i][3] : Stores the length of the longest subsequence (0…1…0…1…) from a[0 to i].

  • Therefore, the answer is the longest subsequence or the maximum of all the 4 given possibilities ( dp[n-1][0], d[n-1][1], dp[n-1][2], dp[n-1][3] ).

Below is the implementation of the above approach:

Python3

## Python program to implement

## the above approach

**import** sys

## Function to find the maximum length

## non decreasing subarray by reversing

## at most one subarray

**def** main(arr, n):

## dp[i][j] be the longest

## subsequence of a[0...i]

## with first j parts

dp **=** [[``0 **for** x **in** range``(n)] **for** y **in** range``(``4``)]

**if** arr[``0``] **==** 0``:

dp[``0``][``0``] **=** 1

**else**``:

dp[``1``][``0``] **=** 1

## Maximum length sub-sequence

## of (0..)

**for** i **in** range``(``1``, n):

**if** arr[i] **==** 0``:

dp[``0``][i] **=** dp[``0``][i``**-**``1``] **+** 1

**else**``:

dp[``0``][i] **=** dp[``0``][i``**-**``1``]

## Maximum length sub-sequence

## of (0..1..)

**for** i **in** range``(``1``, n):

**if** arr[i] **==** 1``:

dp[``1``][i] **=** max``(dp[``1``][i``**-**``1``] **+** 1``, dp[``0``][i``**-**``1``] **+** 1``)

**else**``:

dp[``1``][i] **=** dp[``1``][i``**-**``1``]

## Maximum length sub-sequence

## of (0..1..0..)

**for** i **in** range``(``1``, n):

**if** arr[i] **==** 0``:

dp[``2``][i] **=** max``([dp[``2``][i``**-**``1``] **+** 1``,

dp[``1``][i``**-**``1``] **+** 1``, 

dp[``0``][i``**-**``1``] **+** 1``])

**else**``:

dp[``2``][i] **=** dp[``2``][i``**-**``1``]

## Maximum length sub-sequence

## of (0..1..0..1..)

**for** i **in** range``(``1``, n):

**if** arr[i] **==** 1``:

dp[``3``][i] **=** max``([dp[``3``][i``**-**``1``] **+** 1``,

dp[``2``][i``**-**``1``] **+** 1``, 

dp[``1``][i``**-**``1``] **+** 1``,

dp[``0``][i``**-**``1``] **+** 1``])

**else**``:

dp[``3``][i] **=** dp[``3``][i``**-**``1``]

## Find the max length subsequence

ans **=** max``([dp[``2``][n``**-**``1``], dp[``1``][n``**-**``1``],

dp[``0``][n``**-**``1``], dp[``3``][n``**-**``1``]])

## Print the answer

**print**``(ans)

## Driver Code

**if** __name__ **==** "__main__"``:

n **=** 4

arr **=** [``0``, 1``, 0``, 1``]

main(arr, n)

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 #dynamic programming #subarray #subsequence

What is GEEK

Buddha Community

Maximize length of Non-Decreasing Subsequence by reversing at most one Subarray

Maximize length of Non-Decreasing Subsequence by reversing at most one Subarray

Given a binary array arr[], the task is to find the maximum possible length of non-decreasing subsequence that can be generated by reversing a subarray at most once.

Examples:

Input:_ arr[] = {0, 1, 0, 1}_

_Output: _4

Explanation:

After reversing the subarray from index [2, 3], the array modifies to {0, 0, 1, 1}.

Hence, the longest non-decreasing subsequence is {0, 0, 1, 1}.

Input:_ arr[] = {0, 1, 1, 1, 0, 0, 1, 1, 0}_

_Output: _9

Explanation:

After reversing the subarray from index [2, 6], the array modifies to {0, 0, 0, 1, 1, 1, 1, 1, 0}.

Hence, the longest non-decreasing subsequence is {0, 0, 0, 1, 1, 1, 1, 1}.

Naive Approach: The simplest approach to solve the problem is to reverse each possible subarray in the given array, and find the longest non-decreasing subsequence possible from the array after reversing the subarray.

Time Complexity:_ O(N3)_

Auxiliary Space:_ O(N)_

Efficient Approach: The idea is to use Dynamic Programming to solve the problem. Follow the steps below:

  • Since the array is a binary array the idea is to find the longest subsequence among the subsequences of the forms {0….0}{0…1…}{0…1…0…}, 0…1…0…1.
  • Initialize a dynamic programming table as dp[][] which stores the following:

dp[i][0] : Stores the length of the longest subsequence (0…) from a[0 to i].

dp[i][1] : Stores the length of the longest subsequence (0…1…) from a[0 to i].

dp[i][2] : Stores the length of the longest subsequence (0…1…0…) from a[0 to i].

dp[i][3] : Stores the length of the longest subsequence (0…1…0…1…) from a[0 to i].

  • Therefore, the answer is the longest subsequence or the maximum of all the 4 given possibilities ( dp[n-1][0], d[n-1][1], dp[n-1][2], dp[n-1][3] ).

Below is the implementation of the above approach:

Python3

## Python program to implement

## the above approach

**import** sys

## Function to find the maximum length

## non decreasing subarray by reversing

## at most one subarray

**def** main(arr, n):

## dp[i][j] be the longest

## subsequence of a[0...i]

## with first j parts

dp **=** [[``0 **for** x **in** range``(n)] **for** y **in** range``(``4``)]

**if** arr[``0``] **==** 0``:

dp[``0``][``0``] **=** 1

**else**``:

dp[``1``][``0``] **=** 1

## Maximum length sub-sequence

## of (0..)

**for** i **in** range``(``1``, n):

**if** arr[i] **==** 0``:

dp[``0``][i] **=** dp[``0``][i``**-**``1``] **+** 1

**else**``:

dp[``0``][i] **=** dp[``0``][i``**-**``1``]

## Maximum length sub-sequence

## of (0..1..)

**for** i **in** range``(``1``, n):

**if** arr[i] **==** 1``:

dp[``1``][i] **=** max``(dp[``1``][i``**-**``1``] **+** 1``, dp[``0``][i``**-**``1``] **+** 1``)

**else**``:

dp[``1``][i] **=** dp[``1``][i``**-**``1``]

## Maximum length sub-sequence

## of (0..1..0..)

**for** i **in** range``(``1``, n):

**if** arr[i] **==** 0``:

dp[``2``][i] **=** max``([dp[``2``][i``**-**``1``] **+** 1``,

dp[``1``][i``**-**``1``] **+** 1``, 

dp[``0``][i``**-**``1``] **+** 1``])

**else**``:

dp[``2``][i] **=** dp[``2``][i``**-**``1``]

## Maximum length sub-sequence

## of (0..1..0..1..)

**for** i **in** range``(``1``, n):

**if** arr[i] **==** 1``:

dp[``3``][i] **=** max``([dp[``3``][i``**-**``1``] **+** 1``,

dp[``2``][i``**-**``1``] **+** 1``, 

dp[``1``][i``**-**``1``] **+** 1``,

dp[``0``][i``**-**``1``] **+** 1``])

**else**``:

dp[``3``][i] **=** dp[``3``][i``**-**``1``]

## Find the max length subsequence

ans **=** max``([dp[``2``][n``**-**``1``], dp[``1``][n``**-**``1``],

dp[``0``][n``**-**``1``], dp[``3``][n``**-**``1``]])

## Print the answer

**print**``(ans)

## Driver Code

**if** __name__ **==** "__main__"``:

n **=** 4

arr **=** [``0``, 1``, 0``, 1``]

main(arr, n)

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 #dynamic programming #subarray #subsequence

Hollie  Ratke

Hollie Ratke

1603803600

Maximum subsequence sum obtained by concatenating disjoint subarrays

Given an array arr[] of size **N, **the task is to find the maximum sum of a subsequence formed by concatenating disjoint subarrays whose lengths are prime numbers.

Examples:

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

Output:_ 50_

Explanation:

Subsequence with maximum sum is obtained by concatenating following two subarrays:

  1. {10, 10} of length 2, which is prime.
  2. {10, 10, 10} of length 3, which is prime.

The resulting subsequence is {10, 10, 10, 10, 10}.

Sum of the subsequence is 50.

Input:_ arr[] = {11, 8, 12}_

Output:_ 31_

Naive Approach: The simplest approach is to use recursion to calculate the value of the maximum sum of subsequence. In each step, call multiple recursive calls for each of the prime numbers smaller than N. The recurrence relation is given by:

sum(N) = (arr[N] + arr[N – 1] + … arr[N – P + 1]) + sum(N – P – 1)

where,

P is the prime length of the subarray chosen,

sum(N) is the function that finds the maximum sum of resulting subsequence.

The above recurrence relation is for only one Prime Number. Therefore, there can be more than one possible subsequence can be formed by selecting different subarrays of different prime length. Below is the resulting recurrence relation formed:

sum(N) = max(sum(aN, …, aN-P1+1) + sum(N – P1 – 1), sum(aN, …, aN-P2+1) + sum(N – P2 – 1), …, sum(aN, …, aN-Pk+1) + sum(N – Pk – 1))

where,

P1, P2, … Pk are prime numbers smaller than N.

Time Complexity:_ O(KN) where K is the number of _the _prime numbers smaller than N. Approximately K = (N / LogN) _

Auxiliary Space: O(1)

Dynamic Programming **using Bottom-up Approach: **The recursive calls in the above can also be reduced using an auxiliary array dp[] and calculate the value of each state in the bottom-up approach. Below are the steps:

  • Create an auxiliary array prime[] to store all the prime numbers smaller or equal to N.
  • Maintain the Sieve of Eratosthenes and traverse it to populate the values of array prime[].
  • Create an auxiliary array** dp[] **of size N.
  • Initialize the state 0 and 1 as dp[0] = 0 and dp[1] = 0.
  • Traverse the array dp[] over the range** [2, N]** and update each state as:

_ MSS(i) = max[sum(ai…ai-P1+1) + sum(i-P1-1), sum(ai…ai-P2+1) + sum(i-P2-1), … sum(ai…ai-Pk+1) + sum(i-Pk-1) ] for all prime numbers P1, P2, … Pk smaller than N._

  • Initialize pref[] array to store prefix sum to calculate sum(l, …, r) efficiently.

ai + ai+1 + … aj = sum(i … j) = pref[j] – pref[i – 1]

  • Print the value of dp[N] after the above steps as the result.

Below is the implementation of the above approach:

  • C++

// C++ program for the above approach

#include <bits/stdc++.h>

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

#define MAX 100005

// Function to return all prime numbers

// smaller than N

vector<``**int**``> SieveOfEratosthenes()

{

// Create a boolean array "prime[0..n]"

**bool** seive[MAX];

// Initialize all its entries as true

**memset**``(seive, **true**``, **sizeof**``(seive));

**for** (``**int** p = 2; p * p < MAX; p++) {

// If prime[p] is not changed,

// then it is a prime

**if** (seive[p] == **true**``) {

// Update all multiples of

// p greater than or equal

// to the square of it

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

i < MAX; i += p) {

seive[i] = **false**``;

}

}

}

// Stores all prime numbers

// smaller than MAX

vector<``**int**``> v;

// Store all prime numbers

**for** (``**int** p = 2; p < MAX; p++) {

// If p is prime

**if** (seive[p]) {

v.push_back(p);

}

}

**return** v;

}

// Function to build the auxiliary DP

// array from the start

**void** build(``**int** dp[], **int** arr[], **int** N)

{

// Base Case

dp[0] = 0;

dp[1] = 0;

// Stores all prime numbers < N

vector<``**int**``> prime

= SieveOfEratosthenes();

// Stores prefix sum

**int** pref[N + 1];

pref[0] = 0;

// Update prefix sum

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

pref[i] = pref[i - 1]

+ arr[i - 1];

}

// Iterate over range

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

// Update each state i.e.. when

// current element is excluded

dp[i] = dp[i - 1];

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

j <= prime.size(); j++) {

// Find start & end index

// of subarrays when prime[i]

// is taken

**int** r = i - 1;

**int** l = r - prime[j] + 1;

// Check if starting point

// lies in the array

**if** (l < 0)

**break**``;

**int** temp = 0;

// Include the elements

// al al+1 ... ar

temp = pref[r + 1] - pref[l];

// Check if element lies before

// start of selected subarray

**if** (l - 2 >= 0)

temp += dp[l - 2 + 1];

// Update value of dp[i]

dp[i] = max(dp[i], temp);

}

}

}

// Function to find the maximum sum

// subsequence with prime length

**void** maxSumSubseq(``**int** arr[], **int** N)

{

// Auxiliary DP array

**int** dp[N + 1];

// Build DP array

build(dp, arr, N);

// Print the result

cout << dp[N];

}

// Driver Code

**int** main()

{

// Given arr[]

**int** arr[] = { 10, 10, 7, 10, 10, 10 };

// Size of array

**int** N = **sizeof**``(arr) / **sizeof**``(arr[0]);

// Function Call

maxSumSubseq(arr, N);

**return** 0;

}

Output:

50

Time Complexity:_ O(N * K)_

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 #dynamic programming #recursion #prefix-sum #prime number #sieve #subarray #subsequence

Mikel  Okuneva

Mikel Okuneva

1597935600

Count of subarrays having sum equal to its length

Given an array** arr[]** of size N, the task is to find the number of subarrays having the sum of its elements equal to the number of elements in it.

Examples:

Input: N = 3, arr[] = {1, 0, 2}

Output:_ 3_

Explanation:

Total number of subarrays are 6 i.e., {1}, {0}, {2}, {1, 0}, {0, 2}, {1, 0, 2}.

_Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., _

1) {1}, sum = 1, length = 1.

2) {0, 2}, sum = 2, length = 2.

3) {1, 0, 2}, sum = 3, length = 3.

Input:_ N = 3, arr[] = {1, 1, 0}_

Output:_ 3_

Explanation:

Total number of subarrays are 6 i.e. {1}, {1}, {0}, {1, 1}, {1, 0}, {1, 1, 0}.

_Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., _

1) {1}, sum = 1, length = 1.

2) {1}, sum = 1, length = 1.

3) {1, 1}, sum = 2, length = 2.

Naive Approach: The idea is to generate all the subarrays of the array and if the sum of elements of the subarray is equal to the number of elements in it then count this subarray. Print the count after checking all the subarrays.

_Time Complexity: _O(N2)

Auxiliary Space:_ O(N)_

**Efficient Approach: **This problem can be converted into a simpler problem by using observation. If all the elements of the array are decremented by 1, then all the subarrays of array arr[] with a sum equal to its number of elements are same as finding the number of subarrays with sum 0 in the new array(formed by decrementing all the elements of arr[ ] by 1). Below are the steps:

  1. Decrement all the array elements by 1.
  2. Initialize a prefix array with prefix[0] = arr[0].
  3. Traverse the given array arr[] from left to right, starting from index 1 and update a prefix sum array as pref[i] = pref[i-1] + arr[i].
  4. Initialize the answer to 0.
  5. Iterate the prefix array pref[] from left to right and increment the answer by the value of the current element in the map.
  6. Increment the value of the current element in the map.
  7. Print the value of answer after the above steps.

Below is the implementation of the above approach:

  • C++
  • Python3

// C++ program for the above approach

#include <bits/stdc++.h>

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

// Function that counts the subarrays

// with sum of its elements as its length

**int** countOfSubarray(``**int** arr[], **int** N)

{

// Decrementing all the elements

// of the array by 1

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

arr[i]--;

// Making prefix sum array

**int** pref[N];

pref[0] = arr[0];

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

pref[i] = pref[i - 1] + arr[i];

// Declare map to store count of

// elements upto current element

map<``**int**``, **int**``> mp;

**int** answer = 0;

// To count all the subarrays

// whose prefix sum is 0

mp[0]++;

// Iterate the array

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

// Increment answer by count of

// current element of prefix array

answer += mp[pref[i]];

mp[pref[i]]++;

}

// Return the answer

**return** answer;

}

// Driver Code

**int** main()

{

// Given array arr[]

**int** arr[] = { 1, 1, 0 };

**int** N = **sizeof** arr / **sizeof** arr[0];

// Function call

cout << countOfSubarray(arr, N);

**return** 0;

}

Output:

3

Time Complexity:_ O(N * Log(N))_

Auxiliary Space:_ O(N)_

#arrays #competitive programming #dynamic programming #greedy #mathematical #cpp-map #subarray #subarray-sum

Brain  Crist

Brain Crist

1596646800

Maximum length of subarray consisting of same type of element

Given an array arr[] of N integers, the task is to find the maximum length of sub-array consisting of the same type of element on both halves of the sub-array. Also, the elements on both halves differ from each other.

Examples:

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

_Output: _4

Explanation:

_{2, 3}, {3, 4}, {4, 4, 5, 5}, {5, 6}, etc, are the valid sub-arrays where both halves have only one type of element. _

{4, 4, 5, 5} is the sub-array having maximum length.

_Hence, the output is 4. _

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

_Output: _6

Explanation:

_{1, 7}, {7, 7, 10, 10}, {7, 7, 7, 8, 8, 8}, {8, 9}, etc, are the valid sub-arrays where both halves have only one type of element. _

{7, 7, 7, 8, 8, 8} is the sub-array having maximum length.

_Hence, the output is 6. _

Naive Approach: The naive idea is to generate all possible subarray and check any subarray with maximum length can be divided into two halves such that all the elements in both the halves are the same.

Time Complexity:_ O(N3)_

Auxiliary Space:_ O(1)_

**Efficient Approach: **To solve this problem the idea is to use the concept of Prefix Sum. Follow the steps below to solve the problem:

  1. Traverse the array from the start in the forward direction and store the continuous occurrence of an integer for each index in an array forward[].
  2. Similarly, traverse the array from the end in the reverse direction and store the continuous occurrence of an integer for each index in an array backward[].
  3. Store the maximum of **_min(forward[i], backward[i+1])*2, _**for all the index where arr[i]!=arr[i+1].
  4. Print the value obtained in the above step.

Below is the implementation of the above approach:

  • C++
  • Python3

// C++ program for the above approach

#include <bits/stdc++.h>

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

// Function that finds the maximum

// length of the sub-array that

// contains equal element on both

// halves of sub-array

**void** maxLengthSubArray(``**int** A[], **int** N)

{

// To store continuous occurence

// of the element

**int** forward[N], backward[N];

// To store continuous

// forward occurence

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

**if** (i == 0

|| A[i] != A[i - 1]) {

forward[i] = 1;

}

**else**

forward[i] = forward[i - 1] + 1;

}

// To store continuous

// backward occurence

**for** (``**int** i = N - 1; i >= 0; i--) {

**if** (i == N - 1

|| A[i] != A[i + 1]) {

backward[i] = 1;

}

**else**

backward[i] = backward[i + 1] + 1;

}

// To store the maximum length

**int** ans = 0;

// Find maximum length

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

**if** (A[i] != A[i + 1])

ans = max(ans,

min(forward[i],

backward[i + 1])

* 2);

}

// Print the result

cout << ans;

}

// Driver Code

**int** main()

{

// Given array

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

4, 6, 6, 6, 9 };

// Size of the array

**int** N = **sizeof**``(arr) / **sizeof**``(arr[0]);

// Function Call

maxLengthSubArray(arr, N);

**return** 0;

}

Output:

6

_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 #prefix-sum #subarray #subarray-sum

Siphiwe  Nair

Siphiwe Nair

1623709440

Big Data Follows One Farm, One Data Set Rule Overwhelming To Farmers

The digital world has transformed several businesses with significant impacts on data analytics. The vast type of knowledge available to view is expected to exceed 44 zettabytes by 2022 and has proved to have been of tremendous benefit to several sectors and big companies.

A few companies that get an advantage from big data consulting services are banking, airline, tourism, hospitality, automotive, athletic, entertainment industries, and even the farming sector. The collection could go on and on through big data could be a tremendous possession of an industry expert. By the end of 2021, the company’s acceptance of big data will go to 53 percent. Agriculture struggles to be symbiotic towards the business in the clarification of the information produced.

One industry that can enormously get profit from big data is the rural area. Indeed, the horticultural business likewise can utilize information from numerous points of view and advantage from it extraordinarily. Big data gets an inventive methodology in pretty much every area of the world, so for what reason would horticulture be given up.

Big data is quite an incredible power that it unquestionably can change the agricultural space. Today ranchers must comprehend and esteem innovation to settle on choices all the more rapidly and not linger behind the imaginative methodologies. As smart types of machinery and instruments yield up on farm statistics produce in huge amounts. Possibility, farming developments would develop to be progressively data-enabled as well as data-driven.

#agriculture #big data #latest news #big data follows one farm #one data set rule overwhelming to farmers #big data follows one farm, one data set rule overwhelming to farmers