Longest increasing sequence possible by the boundary elements of an Array
Last Updated :
23 Jul, 2025
Given an array arr[] of length N consisting of positive integers, the task is to find the longest increasing subsequence that can be formed by the elements from either end of the array.
Examples :
Input: N=4 arr[] ={ 1, 4, 2, 3 }
Output: 1 3 4
Explanation:
Append arr[0] to the sequence. Sequence = {1}. Array = {4, 2, 3}.
Append arr[2] to the sequence. Sequence = {1, 3}. Array = {4, 2}.
Append arr[0] to the sequence. Sequence = {1, 3, 4}. Array = {2}.
Therefore, {1, 3, 4} is the longest increasing sequence possible from the given array.
Input: N=3 arr[] ={ 4, 1, 3 }
Output: 3 4
Approach: The idea to solve this problem is to use two pointer approach. Maintain a variable, say rightmost_element, for the rightmost element in the strictly increasing sequence. Keep two pointers at the ends of the array, say i and j respectively and perform the following steps until i surpasses j or elements at both ends are smaller than rightmost_element:
- If arr[i] > arr[j]:
- If arr[j] > rightmost_element: Set rightmost_element = arr[j] and decrement j. Add arr[j] to sequence.
- If arr[i] > rightmost_element: Set rightmost_element = arr[i] and increment i. Add arr[i] to sequence.
- If arr[i] < arr[j]:
- If arr[i] > rightmost_element: Set rightmost_element = arr[i] and increment i. Add arr[i] to sequence.
- If arr[j] > rightmost_element: Set rightmost_element = arr[j] and decrement j. Add arr[j] to sequence.
- If arr[j] = arr[i]:
- If i = j:
- If arr[i]>rightmost_element : Add arr[i] to sequence.
- Otherwise: Check the maximum elements that can be added from the two ends respectively, Let them be max_left and max_right respectively.
- If max_left > max_right: Add all the elements that can be added from the left end.
- Otherwise: Add all the elements that can be added from the right side.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <iostream>
#include <vector>
using namespace std;
// Function to find longest strictly
// increasing sequence using boundary elements
void findMaxLengthSequence(int N, int arr[4])
{
// Maintains rightmost element
// in the sequence
int rightmost_element = -1;
// Pointer to start of array
int i = 0;
// Pointer to end of array
int j = N - 1;
// Stores the required sequence
vector<int> sequence;
// Traverse the array
while (i <= j) {
// If arr[i]>arr[j]
if (arr[i] > arr[j]) {
// If arr[j] is greater than
// rightmost element of the sequence
if (arr[j] > rightmost_element) {
// Push arr[j] into the sequence
sequence.push_back(arr[j]);
// Update rightmost element
rightmost_element = arr[j];
j--;
}
else if (arr[i] > rightmost_element) {
// Push arr[i] into the sequence
sequence.push_back(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
else
break;
}
// If arr[i] < arr[j]
else if (arr[i] < arr[j]) {
// If arr[i] > rightmost element
if (arr[i] > rightmost_element) {
// Push arr[i] into the sequence
sequence.push_back(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
// If arr[j] > rightmost element
else if (arr[j] > rightmost_element) {
// Push arr[j] into the sequence
sequence.push_back(arr[j]);
// Update rightmost element
rightmost_element = arr[j];
j--;
}
else
break;
}
// If arr[i] is equal to arr[j]
else if (arr[i] == arr[j]) {
// If i and j are at the same element
if (i == j) {
// If arr[i] > rightmostelement
if (arr[i] > rightmost_element) {
// Push arr[j] into the sequence
sequence.push_back(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
break;
}
else {
sequence.push_back(arr[i]);
// Traverse array
// from left to right
int k = i + 1;
// Stores the increasing
// sequence from the left end
vector<int> max_left;
// Traverse array from left to right
while (k < j && arr[k] > arr[k - 1]) {
// Push arr[k] to max_left vector
max_left.push_back(arr[k]);
k++;
}
// Traverse the array
// from right to left
int l = j - 1;
// Stores the increasing
// sequence from the right end
vector<int> max_right;
// Traverse array from right to left
while (l > i && arr[l] > arr[l + 1]) {
// Push arr[k] to max_right vector
max_right.push_back(arr[l]);
l--;
}
// If size of max_left is greater
// than max_right
if (max_left.size() > max_right.size())
for (int element : max_left)
// Push max_left elements to
// the original sequence
sequence.push_back(element);
// Otherwise
else
for (int element : max_right)
// Push max_right elements to
// the original sequence
sequence.push_back(element);
break;
}
}
}
// Print the sequence
for (int element : sequence)
printf("%d ", element);
}
// Driver Code
int main()
{
int N = 4;
int arr[] = { 1, 3, 2, 1 };
// Print the longest increasing
// sequence using boundary elements
findMaxLengthSequence(N, arr);
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find longest strictly
// increasing sequence using boundary elements
static void findMaxLengthSequence(int N, int[] arr)
{
// Maintains rightmost element
// in the sequence
int rightmost_element = -1;
// Pointer to start of array
int i = 0;
// Pointer to end of array
int j = N - 1;
// Stores the required sequence
Vector<Integer> sequence = new Vector<Integer>();
// Traverse the array
while (i <= j)
{
// If arr[i]>arr[j]
if (arr[i] > arr[j])
{
// If arr[j] is greater than
// rightmost element of the sequence
if (arr[j] > rightmost_element)
{
// Push arr[j] into the sequence
sequence.add(arr[j]);
// Update rightmost element
rightmost_element = arr[j];
j--;
}
else if (arr[i] > rightmost_element)
{
// Push arr[i] into the sequence
sequence.add(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
else
break;
}
// If arr[i] < arr[j]
else if (arr[i] < arr[j])
{
// If arr[i] > rightmost element
if (arr[i] > rightmost_element)
{
// Push arr[i] into the sequence
sequence.add(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
// If arr[j] > rightmost element
else if (arr[j] > rightmost_element)
{
// Push arr[j] into the sequence
sequence.add(arr[j]);
// Update rightmost element
rightmost_element = arr[j];
j--;
}
else
break;
}
// If arr[i] is equal to arr[j]
else if (arr[i] == arr[j])
{
// If i and j are at the same element
if (i == j)
{
// If arr[i] > rightmostelement
if (arr[i] > rightmost_element)
{
// Push arr[j] into the sequence
sequence.add(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
break;
}
else
{
sequence.add(arr[i]);
// Traverse array
// from left to right
int k = i + 1;
// Stores the increasing
// sequence from the left end
Vector<Integer> max_left = new Vector<Integer>();
// Traverse array from left to right
while (k < j && arr[k] > arr[k - 1])
{
// Push arr[k] to max_left vector
max_left.add(arr[k]);
k++;
}
// Traverse the array
// from right to left
int l = j - 1;
// Stores the increasing
// sequence from the right end
Vector<Integer> max_right = new Vector<Integer>();
// Traverse array from right to left
while (l > i && arr[l] > arr[l + 1])
{
// Push arr[k] to max_right vector
max_right.add(arr[l]);
l--;
}
// If size of max_left is greater
// than max_right
if (max_left.size() > max_right.size())
for(int element : max_left)
// Push max_left elements to
// the original sequence
sequence.add(element);
// Otherwise
else
for(int element : max_right)
// Push max_right elements to
// the original sequence
sequence.add(element);
break;
}
}
}
// Print the sequence
for(int element : sequence)
System.out.print(element + " ");
}
// Driver Code
public static void main(String[] args)
{
int N = 4;
int[] arr = { 1, 3, 2, 1 };
// Print the longest increasing
// sequence using boundary elements
findMaxLengthSequence(N, arr);
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 program for the above approach
# Function to find longest strictly
# increasing sequence using boundary elements
def findMaxLengthSequence(N, arr):
# Maintains rightmost element
# in the sequence
rightmost_element = -1
# Pointer to start of array
i = 0
# Pointer to end of array
j = N - 1
# Stores the required sequence
sequence = []
# Traverse the array
while (i <= j):
# If arr[i]>arr[j]
if (arr[i] > arr[j]):
# If arr[j] is greater than
# rightmost element of the sequence
if (arr[j] > rightmost_element):
# Push arr[j] into the sequence
sequence.append(arr[j])
# Update rightmost element
rightmost_element = arr[j]
j -= 1
elif (arr[i] > rightmost_element):
# Push arr[i] into the sequence
sequence.append(arr[i])
# Update rightmost element
rightmost_element = arr[i]
i += 1
else:
break
# If arr[i] < arr[j]
elif (arr[i] < arr[j]):
# If arr[i] > rightmost element
if (arr[i] > rightmost_element):
# Push arr[i] into the sequence
sequence.append(arr[i])
# Update rightmost element
rightmost_element = arr[i]
i += 1
# If arr[j] > rightmost element
elif (arr[j] > rightmost_element):
# Push arr[j] into the sequence
sequence.append(arr[j])
# Update rightmost element
rightmost_element = arr[j]
j -= 1
else:
break
# If arr[i] is equal to arr[j]
elif (arr[i] == arr[j]):
# If i and j are at the same element
if (i == j):
# If arr[i] > rightmostelement
if (arr[i] > rightmost_element):
# Push arr[j] into the sequence
sequence.append(arr[i])
# Update rightmost element
rightmost_element = arr[i]
i += 1
break
else:
sequence.append(arr[i])
# Traverse array
# from left to right
k = i + 1
# Stores the increasing
# sequence from the left end
max_left = []
# Traverse array from left to right
while (k < j and arr[k] > arr[k - 1]):
# Push arr[k] to max_left vector
max_left.append(arr[k])
k += 1
# Traverse the array
# from right to left
l = j - 1
# Stores the increasing
# sequence from the right end
max_right = []
# Traverse array from right to left
while (l > i and arr[l] > arr[l + 1]):
# Push arr[k] to max_right vector
max_right.append(arr[l])
l -= 1
# If size of max_left is greater
# than max_right
if (len(max_left) > len(max_right)):
for element in max_left:
# Push max_left elements to
# the original sequence
sequence.append(element)
# Otherwise
else:
for element in max_right:
# Push max_right elements to
# the original sequence
sequence.append(element)
break
# Print the sequence
for element in sequence:
print(element, end = " ")
# Driver Code
if __name__ == '__main__':
N = 4
arr = [ 1, 3, 2, 1 ]
# Print the longest increasing
# sequence using boundary elements
findMaxLengthSequence(N, arr)
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find longest strictly
// increasing sequence using boundary elements
static void findMaxLengthSequence(int N, int[] arr)
{
// Maintains rightmost element
// in the sequence
int rightmost_element = -1;
// Pointer to start of array
int i = 0;
// Pointer to end of array
int j = N - 1;
// Stores the required sequence
List<int> sequence = new List<int>();
// Traverse the array
while (i <= j) {
// If arr[i]>arr[j]
if (arr[i] > arr[j]) {
// If arr[j] is greater than
// rightmost element of the sequence
if (arr[j] > rightmost_element) {
// Push arr[j] into the sequence
sequence.Add(arr[j]);
// Update rightmost element
rightmost_element = arr[j];
j--;
}
else if (arr[i] > rightmost_element) {
// Push arr[i] into the sequence
sequence.Add(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
else
break;
}
// If arr[i] < arr[j]
else if (arr[i] < arr[j]) {
// If arr[i] > rightmost element
if (arr[i] > rightmost_element) {
// Push arr[i] into the sequence
sequence.Add(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
// If arr[j] > rightmost element
else if (arr[j] > rightmost_element) {
// Push arr[j] into the sequence
sequence.Add(arr[j]);
// Update rightmost element
rightmost_element = arr[j];
j--;
}
else
break;
}
// If arr[i] is equal to arr[j]
else if (arr[i] == arr[j]) {
// If i and j are at the same element
if (i == j) {
// If arr[i] > rightmostelement
if (arr[i] > rightmost_element) {
// Push arr[j] into the sequence
sequence.Add(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
break;
}
else {
sequence.Add(arr[i]);
// Traverse array
// from left to right
int k = i + 1;
// Stores the increasing
// sequence from the left end
List<int> max_left = new List<int>();
// Traverse array from left to right
while (k < j && arr[k] > arr[k - 1])
{
// Push arr[k] to max_left vector
max_left.Add(arr[k]);
k++;
}
// Traverse the array
// from right to left
int l = j - 1;
// Stores the increasing
// sequence from the right end
List<int> max_right = new List<int>();
// Traverse array from right to left
while (l > i && arr[l] > arr[l + 1])
{
// Push arr[k] to max_right vector
max_right.Add(arr[l]);
l--;
}
// If size of max_left is greater
// than max_right
if (max_left.Count > max_right.Count)
foreach(int element in max_left)
// Push max_left elements to
// the original sequence
sequence.Add(element);
// Otherwise
else
foreach(int element in max_right)
// Push max_right elements to
// the original sequence
sequence.Add(element);
break;
}
}
}
// Print the sequence
foreach(int element in sequence)
Console.Write(element + " ");
}
// Driver code
static void Main()
{
int N = 4;
int[] arr = { 1, 3, 2, 1 };
// Print the longest increasing
// sequence using boundary elements
findMaxLengthSequence(N, arr);
}
}
// This code is contribute by divyesh072019
JavaScript
<script>
// Javascript program for the above approach
// Function to find longest strictly
// increasing sequence using boundary elements
function findMaxLengthSequence(N, arr)
{
// Maintains rightmost element
// in the sequence
let rightmost_element = -1;
// Pointer to start of array
let i = 0;
// Pointer to end of array
let j = N - 1;
// Stores the required sequence
let sequence = [];
// Traverse the array
while (i <= j)
{
// If arr[i]>arr[j]
if (arr[i] > arr[j])
{
// If arr[j] is greater than
// rightmost element of the sequence
if (arr[j] > rightmost_element)
{
// Push arr[j] into the sequence
sequence.push(arr[j]);
// Update rightmost element
rightmost_element = arr[j];
j--;
}
else if (arr[i] > rightmost_element)
{
// Push arr[i] into the sequence
sequence.push(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
else
break;
}
// If arr[i] < arr[j]
else if (arr[i] < arr[j])
{
// If arr[i] > rightmost element
if (arr[i] > rightmost_element)
{
// Push arr[i] into the sequence
sequence.push(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
// If arr[j] > rightmost element
else if (arr[j] > rightmost_element)
{
// Push arr[j] into the sequence
sequence.push(arr[j]);
// Update rightmost element
rightmost_element = arr[j];
j--;
}
else
break;
}
// If arr[i] is equal to arr[j]
else if (arr[i] == arr[j])
{
// If i and j are at the same element
if (i == j)
{
// If arr[i] > rightmostelement
if (arr[i] > rightmost_element)
{
// Push arr[j] into the sequence
sequence.push(arr[i]);
// Update rightmost element
rightmost_element = arr[i];
i++;
}
break;
}
else
{
sequence.push(arr[i]);
// Traverse array
// from left to right
let k = i + 1;
// Stores the increasing
// sequence from the left end
let max_left = [];
// Traverse array from left to right
while (k < j && arr[k] > arr[k - 1])
{
// Push arr[k] to max_left vector
max_left.push(arr[k]);
k++;
}
// Traverse the array
// from right to left
let l = j - 1;
// Stores the increasing
// sequence from the right end
let max_right = [];
// Traverse array from right to left
while (l > i && arr[l] > arr[l + 1])
{
// Push arr[k] to max_right vector
max_right.push(arr[l]);
l--;
}
// If size of max_left is greater
// than max_right
if (max_left.length > max_right.length)
for(let element = 0;
element < max_left.length;
element++)
// Push max_left elements to
// the original sequence
sequence.push(max_left[element]);
// Otherwise
else
for(let element = 0;
element < max_right.length;
element++)
// Push max_right elements to
// the original sequence
sequence.push(max_right[element]);
break;
}
}
}
// Print the sequence
for(let element = 0;
element < sequence.length;
element++)
document.write(sequence[element] + " ");
}
// Driver code
let N = 4;
let arr = [ 1, 3, 2, 1 ];
// Print the longest increasing
// sequence using boundary elements
findMaxLengthSequence(N, arr);
// This code is contributed by suresh07
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem