Count maximum occurrence of subsequence in string such that indices in subsequence is in A.P.
Last Updated :
05 Sep, 2022
Given a string S, the task is to count the maximum occurrence of subsequences in the given string such that the indices of the characters of the subsequence are Arithmetic Progression.
Examples:
Input: S = "xxxyy"
Output: 6
Explanation:
There is a subsequence "xy", where indices of each character of the subsequence are in A.P.
The indices of the different characters that form the subsequence "xy" -
{(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)}
Input: S = "pop"
Output: 2
Explanation:
There is a subsequence "p", where indices of each character of the subsequence are in A.P.
The indices of the different characters that form the subsequence "p" -
{(1), (2)}
Approach: The key observation in the problem is if there are two characters in a string whose collective occurrence is greater than the occurrence of any single character, then these characters will form the maximum occurrence subsequence in the string with the character in, Arithmetic progression because every two integers will always form an arithmetic progression. Below is an illustration of the steps:
- Iterate over the string and count the frequency of the characters of the string. That is considering the subsequences of length 1.
- Iterate over the string and choose every two possible characters of the string and increment the frequency of the subsequence of the string.
- Finally, find the maximum frequency of the subsequence from lengths 1 and 2.
Below is the implementation of the above approach:
C++
// C++ implementation to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
#include <bits/stdc++.h>
using namespace std;
// Function to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
int maximumOccurrence(string s)
{
int n = s.length();
// Frequencies of subsequence
map<string, int> freq;
// Loop to find the frequencies
// of subsequence of length 1
for (int i = 0; i < n; i++) {
string temp = "";
temp += s[i];
freq[temp]++;
}
// Loop to find the frequencies
// subsequence of length 2
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
string temp = "";
temp += s[i];
temp += s[j];
freq[temp]++;
}
}
int answer = INT_MIN;
// Finding maximum frequency
for (auto it : freq)
answer = max(answer, it.second);
return answer;
}
// Driver Code
int main()
{
string s = "xxxyy";
cout << maximumOccurrence(s);
return 0;
}
Java
// Java implementation to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
import java.util.*;
class GFG
{
// Function to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
static int maximumOccurrence(String s)
{
int n = s.length();
// Frequencies of subsequence
HashMap<String, Integer> freq = new HashMap<String,Integer>();
int i, j;
// Loop to find the frequencies
// of subsequence of length 1
for ( i = 0; i < n; i++) {
String temp = "";
temp += s.charAt(i);
if (freq.containsKey(temp)){
freq.put(temp,freq.get(temp)+1);
}
else{
freq.put(temp, 1);
}
}
// Loop to find the frequencies
// subsequence of length 2
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
String temp = "";
temp += s.charAt(i);
temp += s.charAt(j);
if(freq.containsKey(temp))
freq.put(temp,freq.get(temp)+1);
else
freq.put(temp,1);
}
}
int answer = Integer.MIN_VALUE;
// Finding maximum frequency
for (int it : freq.values())
answer = Math.max(answer, it);
return answer;
}
// Driver Code
public static void main(String []args)
{
String s = "xxxyy";
System.out.print(maximumOccurrence(s));
}
}
// This code is contributed by chitranayal
Python3
# Python3 implementation to find the
# maximum occurrence of the subsequence
# such that the indices of characters
# are in arithmetic progression
# Function to find the
# maximum occurrence of the subsequence
# such that the indices of characters
# are in arithmetic progression
def maximumOccurrence(s):
n = len(s)
# Frequencies of subsequence
freq = {}
# Loop to find the frequencies
# of subsequence of length 1
for i in s:
temp = ""
temp += i
freq[temp] = freq.get(temp, 0) + 1
# Loop to find the frequencies
# subsequence of length 2
for i in range(n):
for j in range(i + 1, n):
temp = ""
temp += s[i]
temp += s[j]
freq[temp] = freq.get(temp, 0) + 1
answer = -10**9
# Finding maximum frequency
for it in freq:
answer = max(answer, freq[it])
return answer
# Driver Code
if __name__ == '__main__':
s = "xxxyy"
print(maximumOccurrence(s))
# This code is contributed by mohit kumar 29
C#
// C# implementation to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
static int maximumOccurrence(string s)
{
int n = s.Length;
// Frequencies of subsequence
Dictionary<string,
int> freq = new Dictionary<string,
int>();
int i, j;
// Loop to find the frequencies
// of subsequence of length 1
for ( i = 0; i < n; i++)
{
string temp = "";
temp += s[i];
if (freq.ContainsKey(temp))
{
freq[temp]++;
}
else
{
freq[temp] = 1;
}
}
// Loop to find the frequencies
// subsequence of length 2
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
string temp = "";
temp += s[i];
temp += s[j];
if(freq.ContainsKey(temp))
freq[temp]++;
else
freq[temp] = 1;
}
}
int answer =int.MinValue;
// Finding maximum frequency
foreach(KeyValuePair<string,
int> it in freq)
answer = Math.Max(answer, it.Value);
return answer;
}
// Driver Code
public static void Main(string []args)
{
string s = "xxxyy";
Console.Write(maximumOccurrence(s));
}
}
// This code is contributed by Rutvik_56
JavaScript
<script>
// Javascript implementation to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
// Function to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
function maximumOccurrence(s)
{
var n = s.length;
// Frequencies of subsequence
var freq = new Map();
// Loop to find the frequencies
// of subsequence of length 1
for (var i = 0; i < n; i++) {
var temp = "";
temp += s[i];
if(freq.has(temp))
freq.set(temp, freq.get(temp)+1)
else
freq.set(temp, 1)
}
// Loop to find the frequencies
// subsequence of length 2
for (var i = 0; i < n; i++) {
for (var j = i + 1; j < n; j++) {
var temp = "";
temp += s[i];
temp += s[j];
if(freq.has(temp))
freq.set(temp, freq.get(temp)+1)
else
freq.set(temp, 1)
}
}
var answer = -1000000000;
// Finding maximum frequency
freq.forEach((value, key) => {
answer = Math.max(answer, value);
});
return answer;
}
// Driver Code
var s = "xxxyy";
document.write( maximumOccurrence(s));
</script>
Time Complexity: O(N2), for using two nested loops.
Auxiliary Space: O(N), where N is the size of the given string.
Efficient Approach: The idea is to use the dynamic programming paradigm to compute the frequency of the subsequences of lengths 1 and 2 in the string. Below is an illustration of the steps:
- Compute the frequency of the characters of the string in a frequency array.
- For subsequences of the string of length 2, the DP state will be
dp[i][j] = Total number of times ith
character occurred before jth character.
Below is the implementation of the above approach:
C++
// C++ implementation to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
#include <bits/stdc++.h>
using namespace std;
// Function to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
int maximumOccurrence(string s)
{
int n = s.length();
// Frequency for characters
int freq[26] = { 0 };
int dp[26][26] = { 0 };
// Loop to count the occurrence
// of ith character before jth
// character in the given string
for (int i = 0; i < n; i++) {
int c = (s[i] - 'a');
for (int j = 0; j < 26; j++)
dp[c][j] += freq[j];
// Increase the frequency
// of s[i] or c of string
freq[c]++;
}
int answer = INT_MIN;
// Maximum occurrence of subsequence
// of length 1 in given string
for (int i = 0; i < 26; i++)
answer = max(answer, freq[i]);
// Maximum occurrence of subsequence
// of length 2 in given string
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
answer = max(answer, dp[i][j]);
}
}
return answer;
}
// Driver Code
int main()
{
string s = "xxxyy";
cout << maximumOccurrence(s);
return 0;
}
Java
// Java implementation to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
class GFG{
// Function to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
static int maximumOccurrence(String s)
{
int n = s.length();
// Frequency for characters
int freq[] = new int[26];
int dp[][] = new int[26][26];
// Loop to count the occurrence
// of ith character before jth
// character in the given String
for (int i = 0; i < n; i++) {
int c = (s.charAt(i) - 'a');
for (int j = 0; j < 26; j++)
dp[c][j] += freq[j];
// Increase the frequency
// of s[i] or c of String
freq[c]++;
}
int answer = Integer.MIN_VALUE;
// Maximum occurrence of subsequence
// of length 1 in given String
for (int i = 0; i < 26; i++)
answer = Math.max(answer, freq[i]);
// Maximum occurrence of subsequence
// of length 2 in given String
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
answer = Math.max(answer, dp[i][j]);
}
}
return answer;
}
// Driver Code
public static void main(String[] args)
{
String s = "xxxyy";
System.out.print(maximumOccurrence(s));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation to find the
# maximum occurrence of the subsequence
# such that the indices of characters
# are in arithmetic progression
import sys
# Function to find the maximum occurrence
# of the subsequence such that the
# indices of characters are in
# arithmetic progression
def maximumOccurrence(s):
n = len(s)
# Frequency for characters
freq = [0] * (26)
dp = [[0 for i in range(26)]
for j in range(26)]
# Loop to count the occurrence
# of ith character before jth
# character in the given String
for i in range(n):
c = (ord(s[i]) - ord('a'))
for j in range(26):
dp[c][j] += freq[j]
# Increase the frequency
# of s[i] or c of String
freq[c] += 1
answer = -sys.maxsize
# Maximum occurrence of subsequence
# of length 1 in given String
for i in range(26):
answer = max(answer, freq[i])
# Maximum occurrence of subsequence
# of length 2 in given String
for i in range(26):
for j in range(26):
answer = max(answer, dp[i][j])
return answer
# Driver Code
if __name__ == '__main__':
s = "xxxyy"
print(maximumOccurrence(s))
# This code is contributed by Princi Singh
C#
// C# implementation to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
using System;
class GFG{
// Function to find the maximum
// occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
static int maximumOccurrence(string s)
{
int n = s.Length;
// Frequency for characters
int []freq = new int[26];
int [,]dp = new int[26, 26];
// Loop to count the occurrence
// of ith character before jth
// character in the given String
for(int i = 0; i < n; i++)
{
int x = (s[i] - 'a');
for(int j = 0; j < 26; j++)
dp[x, j] += freq[j];
// Increase the frequency
// of s[i] or c of String
freq[x]++;
}
int answer = int.MinValue;
// Maximum occurrence of subsequence
// of length 1 in given String
for(int i = 0; i < 26; i++)
answer = Math.Max(answer, freq[i]);
// Maximum occurrence of subsequence
// of length 2 in given String
for(int i = 0; i < 26; i++)
{
for(int j = 0; j < 26; j++)
{
answer = Math.Max(answer, dp[i, j]);
}
}
return answer;
}
// Driver Code
public static void Main(string[] args)
{
string s = "xxxyy";
Console.Write(maximumOccurrence(s));
}
}
// This code is contributed by Yash_R
JavaScript
<script>
// javascript implementation to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
// Function to find the
// maximum occurrence of the subsequence
// such that the indices of characters
// are in arithmetic progression
function maximumOccurrence(s) {
var n = s.length;
// Frequency for characters
var freq = Array(26).fill(0);
var dp = Array(26).fill().map(()=>Array(26).fill(0));
// Loop to count the occurrence
// of ith character before jth
// character in the given String
for (var i = 0; i < n; i++) {
var c = (s.charCodeAt(i) - 'a'.charCodeAt(0));
for (var j = 0; j < 26; j++)
dp[c][j] += freq[j];
// Increase the frequency
// of s[i] or c of String
freq[c]++;
}
var answer = Number.MIN_VALUE;
// Maximum occurrence of subsequence
// of length 1 in given String
for (var i = 0; i < 26; i++)
answer = Math.max(answer, freq[i]);
// Maximum occurrence of subsequence
// of length 2 in given String
for (var i = 0; i < 26; i++) {
for (var j = 0; j < 26; j++) {
answer = Math.max(answer, dp[i][j]);
}
}
return answer;
}
// Driver Code
var s = "xxxyy";
document.write(maximumOccurrence(s));
// This code contributed by Princi Singh
</script>
Time complexity: O(26 * N)
Auxiliary space: O(1) as constant space is required by the algorithm.
Similar Reads
Count of maximum occurring subsequence using only those characters whose indices are in GP
Given a string S, the task is to find the count of maximum occurring subsequence P from S using only those characters whose indexes are in Geometric Progression.Note: Consider 1-based indexing in S. Examples : Input: S = "ddee"Output: 4Explanation: If we take P = "de", then P occurs 4 times in S. {
7 min read
Minimize count of alternating subsequences to divide given Binary String with subsequence number
Given a binary string S of length N. The task is to find the following: The minimum number of subsequences, string S can be divided into, such that the subsequence does not contain adjacent zeroes or ones.Subsequence number to which each character of string S belongs. If there are many answers, outp
11 min read
Maximize count of 3-length palindromic subsequences with each index part of a single subsequence
Given a string, S, the task is to find the maximum number of distinct indexed palindromic subsequences of length 3 possible from the given string. Examples: Input: str = âgeekforgâOutput: 2Explanation:Possible palindromic subsequences of length 3 satisfying the conditions are "gkg" and "efe". Theref
6 min read
Frequency of maximum occurring subsequence in given string
Given a string str of lowercase English alphabets, our task is to find the frequency of occurrence a subsequence of the string which occurs the maximum times. Examples: Input: s = "aba" Output: 2 Explanation: For "aba", subsequence "ab" occurs maximum times in subsequence 'ab' and 'aba'. Input: s =
6 min read
Count of unique Subsequences of given String with lengths in range [0, N]
Given a string S of length N, the task is to find the number of unique subsequences of the string for each length from 0 to N. Note: The uppercase letters and lowercase letters are considered different and the result may be large so print it modulo 1000000007. Examples: Input: S = "ababd"Output: Num
14 min read
Find number of times a string occurs as a subsequence in given string
Given two strings, find the number of times the second string occurs in the first string, whether continuous or discontinuous.Examples: Input: string a = "GeeksforGeeks"string b = "Gks"Output: 4Explanation: The four strings are - (Check characters marked in bold)GeeksforGeeksGeeksforGeeksGeeksforGee
15+ min read
Count occurrences of substring X before every occurrence of substring Y in a given string
Given three strings S, X, and Y consisting of N, A, and B characters respectively, the task is to find the number of occurrences of the substring X before every occurrence of the substring Y in the given string S. Examples: Input S = âabcdefdefabcâ, X = âdefâ, Y = âabcâOutput: 0 2Explanation:First o
6 min read
Find the equal pairs of subsequence of S and subsequence of T
Given two arrays S[] and T[] of size N and M respectively. The task is to find the pairs of subsequences of S[] and subsequences of T[] which are the same in content. Answer could be very large. So, print the answer modulo 109 + 7.Examples: Input: S[] = {1, 1}, T[] = {1, 1} Output: 6 Subsequences of
13 min read
Count binary Strings that does not contain given String as Subsequence
Given a number N and string S, count the number of ways to create a binary string (containing only '0' and '1') of size N such that it does not contain S as a subsequence. Examples: Input: N = 3, S = "10".Output: 4Explanation: There are 8 strings possible to fill 3 positions with 0's or 1's. {"000",
15+ min read
Maximize subsequences having array elements not exceeding length of the subsequence
Given an array arr[] consisting of N positive integers, the task is to maximize the number of subsequences that can be obtained from an array such that every element arr[i] that is part of any subsequence does not exceed the length of that subsequence. Examples: Input: arr[] = {1, 1, 1, 1} Output: 4
6 min read