
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximum size of sub-array that satisfies the given condition in C++
In this tutorial, we will be discussing a program to find maximum size of sub-array that satisfies the given condition.
For this we will be provided with an array of integers. Our task is to find the maximum length subset of that array satisfying either of arr[k] > arr[k + 1] when k is odd and arr[k] < arr[k + 1] when k is even, arr[k] > arr[k + 1] when k is even and arr[k] < arr[k + 1] when k is odd.
Example
#include<bits/stdc++.h> using namespace std; //comparing values of a and b int cmp(int a, int b) { return (a > b) - (a < b); } //returning longest substring int maxSubarraySize(int arr[], int n) { int ans = 1; int anchor = 0; for (int i = 1; i < n; i++) { int c = cmp(arr[i - 1], arr[i]); if (c == 0) anchor = i; else if (i == n - 1 || c * cmp(arr[i], arr[i + 1]) != -1) { ans = max(ans, i - anchor + 1); anchor = i; } } return ans; } int main() { int arr[] = {9, 4, 2, 10, 7, 8, 8, 1, 9}; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSubarraySize(arr, n); }
Output
5
- Related Articles
- Maximum size of sub-array that satisfies the given condition in C++ program
- Find permutation of first N natural numbers that satisfies the given condition in C++
- Print maximum sum square sub-matrix of given size in C Program.
- Maximum product quadruple (sub-sequence of size 4) in array in C++
- Find the lexicographically smallest string which satisfies the given condition in Python
- Find Maximum XOR value of a sub-array of size k in C++
- Finding the sub array that has maximum sum JavaScript
- C# Program to return the only element that satisfies a condition
- Maximum number of Unique integers in Sub- Array of given sizes in C++
- Find maximum of minimum for every window size in a given array in C++
- Maximum size rectangle binary sub-matrix with all 1s in C++
- Queries on number of Binary sub-matrices of Given size in C++
- Maximum trace possible for any sub-matrix of the given matrix in C++
- How to find the number of columns of an R data frame that satisfies a condition based on row values?
- Maximum size rectangle binary sub-matrix with all 1s in C++ Program

Advertisements