Longest Subsequence such that difference between adjacent elements is either A or B
Last Updated :
20 Dec, 2021
Given an array arr of size N, and two integers A and B. The task is to find the length of the longest subsequence with the difference between adjacent elements as either A or B.
Example:
Input : arr[]={ 5, 5, 5, 10, 8, 6, 12, 13 }, A=0, B=1
Output : 4
Explanation : Maximum length subsequence is {5,5,5,6}
Input : arr[] = {4, 6, 7, 8, 9, 8, 12, 14, 17, 15}, A=2, B=1
Output : 6
Approach: On taking a closer look at the problem, the problem is similar to Longest Consecutive Subsequence. The only difference between them is now we have to count for the elements with differences A or B instead of 1. Now, to solve this problem, follow the below steps:
- Create a map, which will store each element as the key, and the length of the longest subsequence ending with arr[i] as the value.
- Now, traverse the array arr, and for each element arr[i]:
- Search for arr[i]-A, arr[i]+A, arr[i]-B, arr[i]+B in the map.
- If they are present find the maximum of all and +1 in that to get the maximum length of subsequence.
- Find the maximum value in the map, and return it as the answer
Below is the implementation of the above approach.
C++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the length of
// longest common subsequence with
// difference between the consecutive
// element is either A or B
int maxSubsequence(vector<int>& arr, int A, int B)
{
int N = arr.size();
int ans = 1;
// Map to store the length of longest subsequence
// ending with arr[i]
unordered_map<int, int> mp;
for (int i = 0; i < N; ++i) {
int aa = 1;
// If arr[i]-A exists
if (mp.count(arr[i] - A)) {
aa = mp[arr[i] - A] + 1;
}
// If arr[i]+A exists
if (mp.count(arr[i] + A)) {
aa = max(aa, mp[arr[i] + A] + 1);
}
// If arr[i]-B exists
if (mp.count(arr[i] - B)) {
aa = max(aa, mp[arr[i] - B] + 1);
}
// If arr[i]+B exists
if (mp.count(arr[i] + B)) {
aa = max(aa, mp[arr[i] + B] + 1);
}
mp[arr[i]] = aa;
ans = max(ans, mp[arr[i]]);
}
return ans;
}
// Driver Code
int main()
{
vector<int> arr = { 5, 5, 5, 10, 8, 6, 12, 13 };
int A = 0, B = 1;
cout << maxSubsequence(arr, A, B);
return 0;
}
Java
// Java code for the above approach
import java.util.*;
class GFG{
// Function to find the length of
// longest common subsequence with
// difference between the consecutive
// element is either A or B
static int maxSubsequence(int []arr, int A, int B)
{
int N = arr.length;
int ans = 1;
// Map to store the length of longest subsequence
// ending with arr[i]
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
for (int i = 0; i < N; ++i) {
int aa = 1;
// If arr[i]-A exists
if (mp.containsKey(arr[i] - A)) {
aa = mp.get(arr[i] - A) + 1;
}
// If arr[i]+A exists
if (mp.containsKey(arr[i] + A)) {
aa = Math.max(aa, mp.get(arr[i] + A) + 1);
}
// If arr[i]-B exists
if (mp.containsKey(arr[i] - B)) {
aa = Math.max(aa, mp.get(arr[i] - B) + 1);
}
// If arr[i]+B exists
if (mp.containsKey(arr[i] + B)) {
aa = Math.max(aa, mp.get(arr[i] + B) + 1);
}
mp.put(arr[i], aa);
ans = Math.max(ans, mp.get(arr[i]));
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int []arr = { 5, 5, 5, 10, 8, 6, 12, 13 };
int A = 0, B = 1;
System.out.print(maxSubsequence(arr, A, B));
}
}
// This code is contributed by 29AjayKumar
Python3
# python code for the above approach
# Function to find the length of
# longest common subsequence with
# difference between the consecutive
# element is either A or B
def maxSubsequence(arr, A, B):
N = len(arr)
ans = 1
# Map to store the length of longest subsequence
# ending with arr[i]
mp = {}
for i in range(0, N):
aa = 1
# If arr[i]-A exists
if ((arr[i] - A) in mp):
aa = mp[arr[i] - A] + 1
# If arr[i]+A exists
if ((arr[i] + A) in mp):
aa = max(aa, mp[arr[i] + A] + 1)
# If arr[i]-B exists
if ((arr[i] - B) in mp):
aa = max(aa, mp[arr[i] - B] + 1)
# If arr[i]+B exists
if ((arr[i] + B) in mp):
aa = max(aa, mp[arr[i] + B] + 1)
mp[arr[i]] = aa
ans = max(ans, mp[arr[i]])
return ans
# Driver Code
if __name__ == "__main__":
arr = [5, 5, 5, 10, 8, 6, 12, 13]
A = 0
B = 1
print(maxSubsequence(arr, A, B))
# This code is contributed by rakeshsahni
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
class GFG {
// Function to find the length of
// longest common subsequence with
// difference between the consecutive
// element is either A or B
static int maxSubsequence(int[] arr, int A, int B)
{
int N = arr.Length;
int ans = 1;
// Map to store the length of longest subsequence
// ending with arr[i]
Dictionary<int, int> mp
= new Dictionary<int, int>();
for (int i = 0; i < N; ++i) {
int aa = 1;
// If arr[i]-A exists
if (mp.ContainsKey(arr[i] - A)) {
aa = mp[arr[i] - A] + 1;
}
// If arr[i]+A exists
if (mp.ContainsKey(arr[i] + A)) {
aa = Math.Max(aa, mp[arr[i] + A] + 1);
}
// If arr[i]-B exists
if (mp.ContainsKey(arr[i] - B)) {
aa = Math.Max(aa, mp[arr[i] - B] + 1);
}
// If arr[i]+B exists
if (mp.ContainsKey(arr[i] + B)) {
aa = Math.Max(aa, mp[arr[i] + B] + 1);
}
mp[arr[i]] = aa;
ans = Math.Max(ans, mp[arr[i]]);
}
return ans;
}
// Driver Code
public static void Main(string[] args)
{
int[] arr = { 5, 5, 5, 10, 8, 6, 12, 13 };
int A = 0, B = 1;
Console.WriteLine(maxSubsequence(arr, A, B));
}
}
// This code is contributed by ukasp.
JavaScript
<script>
// JavaScript code for the above approach
// Function to find the length of
// longest common subsequence with
// difference between the consecutive
// element is either A or B
function maxSubsequence(arr, A, B) {
let N = arr.length;
let ans = 1;
// Map to store the length of longest subsequence
// ending with arr[i]
let mp = new Map();
for (let i = 0; i < N; ++i) {
let aa = 1;
// If arr[i]-A exists
if (mp.has(arr[i] - A)) {
aa = mp.get(arr[i] - A) + 1;
}
// If arr[i]+A exists
if (mp.has(arr[i] + A)) {
aa = Math.max(aa, mp.get(arr[i] + A) + 1);
}
// If arr[i]-B exists
if (mp.has(arr[i] - B)) {
aa = Math.max(aa, mp.get(arr[i] - B) + 1);
}
// If arr[i]+B exists
if (mp.has(arr[i] + B)) {
aa = Math.max(aa, mp.get(arr[i] + B) + 1);
}
mp.set(arr[i], aa);
ans = Math.max(ans, mp.get(arr[i]));
}
return ans;
}
// Driver Code
let arr = [5, 5, 5, 10, 8, 6, 12, 13]
let A = 0, B = 1;
document.write(maxSubsequence(arr, A, B));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read