Optimizing Arithmetic Progressions in Subsequences
Last Updated :
29 Jan, 2024
Given a string S, a string T is considered good if following 2 conditions hold:
For example, if S = "aaabb" then T = "aab" is good because T is subsequence of S at indices 1,3,5 which is an arithmetic progression. The task is to determine any subsequence that is good string having highest occurrences in the string. Print the number of times that subsequence appears as a good string in the given string.
Examples:
Input: S = "aaabb"
Output: 6
Explanation: "ab" is the good strings with the highest number of occurrences. "ab" occurred 6 times at (1,4), (1,5), (2,4), (2,5), (3,4) and (3,5)
Input: "abcde"
Output: 1
Explanation: "a" is the good string which occurred only once.
Observations:
We observe that if the good string that occurs the most times has length > 2, then there must exist one that occurs just as many times of length exactly 2. This is true because we can always just take the first 2 letters of the good string and still get the answer. Therefore, we only need to check strings of lengths 1 and 2.
Approach: The problem can be solved using the following approach:
The intuition is based on the properties of subsequences and arithmetic progressions. Here's the key idea:
- The problem asks for a good subsequence, which is defined as a subsequence where the indices form an arithmetic progression. This means that the characters in the subsequence are evenly spaced in the original string.
- Count the frequency of each character and each pair of characters in the string. we'll use two arrays, arr1 and arr2, to store these frequencies. arr1[c][/c] is the frequency of character c, and arr2[i][j] is the frequency of pairs of characters i and j where j appears after i in the string.
- Now, iterate over the string and for each character, updates the frequency of that character and all pairs that can be formed with that character. After that, finds the maximum frequency among all characters and all pairs of characters. This maximum frequency is the number of times the most frequent good subsequence appears in the string.
This approach will work because a good subsequence can be either a single character or a pair of characters. A single character is always a good subsequence, and a pair of characters is a good subsequence if and only if the two characters appear at indices that form an arithmetic progression. By counting the frequency of each character and each pair of characters, the code effectively counts the frequency of all possible good subsequences.
Steps to solve the problem:
- Initialize two arrays, arr1 and arr2. arr1 is a 1D array that will store the frequency of each character in the string. arr2 is a 2D array that will store the frequency of each pair of characters in the string.
- Iterate over each character in the string. For each character, do the following:
- Convert the current character to its corresponding index (0-25) by subtracting 'a' from it.
- For each character, add its frequency to the count of pairs with the current character. This is done by adding arr1[j] to arr2[j][c][/c] for all j.
- Increment the frequency of the current character. This is done by incrementing arr1[c][/c].
- Initialize a variable ans to 0.
- Find the maximum frequency among all characters.
- Find the maximum frequency among all pairs of characters.
- Print the maximum frequency, which is the number of times the most frequent good subsequence appears in the string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// Declare arrays to store the frequency of characters and
// pairs of characters
ll arr1[26], arr2[26][26];
int main()
{
string S = "aaabb";
// Iterate over the string
for (int i = 0; i < S.length(); i++) {
// Convert the current character to its
// corresponding index (0-25)
int c = S[i] - 'a';
// For each character, add its frequency to the
// count of pairs with the current character
for (int j = 0; j < 26; j++)
arr2[j][c] += arr1[j];
// Increment the frequency of the current character
arr1[c]++;
}
// Initialize the maximum frequency to 0
ll ans = 0;
// Find the maximum frequency among all characters
for (int i = 0; i < 26; i++)
ans = max(ans, arr1[i]);
// Find the maximum frequency among all pairs of
// characters
for (int i = 0; i < 26; i++)
for (int j = 0; j < 26; j++)
ans = max(ans, arr2[i][j]);
cout << ans << endl; // Print the maximum frequency
}
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
String S = "aaabb";
// Declare arrays to store the frequency of
// characters and pairs of characters
long[] arr1 = new long[26];
long[][] arr2 = new long[26][26];
// Iterate over the string
for (int i = 0; i < S.length(); i++) {
// Convert the current character to its
// corresponding index (0-25)
int c = S.charAt(i) - 'a';
// For each character, add its frequency to the
// count of pairs with the current character
for (int j = 0; j < 26; j++)
arr2[j][c] += arr1[j];
// Increment the frequency of the current
// character
arr1[c]++;
}
// Initialize the maximum frequency to 0
long ans = 0;
// Find the maximum frequency among all characters
for (int i = 0; i < 26; i++)
ans = Math.max(ans, arr1[i]);
// Find the maximum frequency among all pairs of
// characters
for (int i = 0; i < 26; i++)
for (int j = 0; j < 26; j++)
ans = Math.max(ans, arr2[i][j]);
System.out.println(
ans); // Print the maximum frequency
}
}
Python
# Initialize arrays to store the frequency of characters and pairs of characters
arr1 = [0] * 26
arr2 = [[0] * 26 for _ in range(26)]
# Input string
S = "aaabb"
# Iterate over the string
for i in range(len(S)):
# Convert the current character to its corresponding index (0-25)
c = ord(S[i]) - ord('a')
# For each character, add its frequency to the count of pairs with the current character
for j in range(26):
arr2[j][c] += arr1[j]
# Increment the frequency of the current character
arr1[c] += 1
# Initialize the maximum frequency to 0
ans = 0
# Find the maximum frequency among all characters
for i in range(26):
ans = max(ans, arr1[i])
# Find the maximum frequency among all pairs of characters
for i in range(26):
for j in range(26):
ans = max(ans, arr2[i][j])
print(ans) # Print the maximum frequency
C#
using System;
class GFG {
public static void Main (string[] args) {
string S = "aaabb";
// Declare arrays to store the frequency of characters and
// pairs of characters
long[] arr1 = new long[26];
long[,] arr2 = new long[26, 26];
// Iterate over the string
for (int i = 0; i < S.Length; i++) {
// Convert the current character to its
// corresponding index (0-25)
int c = S[i] - 'a';
// For each character, add its frequency to the
// count of pairs with the current character
for (int j = 0; j < 26; j++)
arr2[j, c] += arr1[j];
// Increment the frequency of the current character
arr1[c]++;
}
// Initialize the maximum frequency to 0
long ans = 0;
// Find the maximum frequency among all characters
for (int i = 0; i < 26; i++)
ans = Math.Max(ans, arr1[i]);
// Find the maximum frequency among all pairs of
// characters
for (int i = 0; i < 26; i++)
for (int j = 0; j < 26; j++)
ans = Math.Max(ans, arr2[i, j]);
Console.WriteLine(ans); // Print the maximum frequency
}
}
JavaScript
function findMaxFrequency(S) {
// Declare arrays to store the frequency of characters and pairs of characters
const arr1 = new Array(26).fill(0);
const arr2 = new Array(26).fill(null).map(() => new Array(26).fill(0));
// Iterate over the string
for (let i = 0; i < S.length; i++) {
// Convert the current character to its corresponding index (0-25)
const c = S.charCodeAt(i) - 'a'.charCodeAt(0);
// For each character, add its frequency to the count of pairs with the current character
for (let j = 0; j < 26; j++) {
arr2[j][c] += arr1[j];
}
// Increment the frequency of the current character
arr1[c]++;
}
// Initialize the maximum frequency to 0
let ans = 0;
// Find the maximum frequency among all characters
for (let i = 0; i < 26; i++) {
ans = Math.max(ans, arr1[i]);
}
// Find the maximum frequency among all pairs of characters
for (let i = 0; i < 26; i++) {
for (let j = 0; j < 26; j++) {
ans = Math.max(ans, arr2[i][j]);
}
}
return ans; // Return the maximum frequency
}
// Example usage
const S = "aaabb";
const result = findMaxFrequency(S);
console.log(result); // Print the maximum frequency
Time Complexity: O(N), where N is the length of the input string S.
Auxiliary Space: O(1)
Similar Reads
Longest subsequence forming an Arithmetic Progression (AP)
Given an array arr[] consisting of N integers, the task is to find the length of the longest subsequence that forms an Arithmetic Progression. Examples: Input: arr[] = {5, 10, 15, 20, 25, 30}Output: 6Explanation:The whole set is in AP having common difference = 5.Therefore, the length is 4. Input: a
13 min read
Count of AP (Arithmetic Progression) Subsequences in an array
Given an array arr[] of n positive integers. The task is to count the number of Arithmetic Progression subsequences in the array. Note: Empty sequence or single element sequence is Arithmetic Progression.Examples: Input: arr[] = [1, 2, 3]Output: 8Explanation: Arithmetic Progression subsequence from
15+ min read
Practice Questions on Arithmetic Progression (Basic)
An arithmetic progression (AP), also known as an arithmetic sequence, is a sequence of numbers in which the difference between consecutive terms is constant. This constant difference is called the "common difference."Important Formulas on Arithmetic ProgressionVarious formulas on arithmetic progress
9 min read
Find the missing number in Arithmetic Progression
Given an array arr[] that represents elements of arithmetic progression in order. One element is missing in the progression, find the missing number. Note: An element will always exist that, upon inserting into a sequence forms Arithmetic progression. If the given sequence already forms a valid comp
15+ min read
Program to print Arithmetic Progression series
Given first term (a), common difference (d) and a integer n of the Arithmetic Progression series, the task is to print the series. Examples : Input : a = 5, d = 2, n = 10Output : 5 7 9 11 13 15 17 19 21 23Approach : We know the Arithmetic Progression series is like = 2, 5, 8, 11, 14 â¦. ⦠In this ser
4 min read
Arithmetic Progression in Maths
Arithmetic Progression (AP) or Arithmetic Sequence is simply a sequence of numbers such that the difference between any two consecutive terms is constant.Some Real World Examples of APNatural Numbers: 1, 2, 3, 4, 5, . . . with a common difference 1Even Numbers: 2, 4, 6, 8, 10, . . . with a common di
3 min read
Count of subarrays forming an Arithmetic Progression (AP)
Given an array arr[] of size N, the task is to find the count of subarrays of at least length 2, such that the difference between the consecutive elements of those subarrays remains the same throughout i.e. the elements of the subarray forms an AP. Examples: Input: arr[] = {8, 7, 4, 1, 0} Output: 5
15 min read
Longest Arithmetic Progression
Given an array arr[] of sorted integers and distinct positive integers, find the length of the Longest Arithmetic Progression in it.Note: A sequence seq is an arithmetic progression if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).Examples: Input: arr[] = [1, 7, 10,
15+ min read
Minimize Nth term of an Arithmetic progression (AP)
Given two integers A, B which are any two terms of an Arithmetic Progression series, and an integer N, the task is to minimize the Nth term of that arithmetic progression. Note: All the elements of an AP series must be positive. Examples: Input: A = 1, B = 6, N = 3Output: 11Explanations: First three
7 min read
Number of GP (Geometric Progression) subsequences of size 3
Given n elements and a ratio r, find the number of G.P. subsequences with length 3. A subsequence is considered GP with length 3 with ration r. Examples: Input : arr[] = {1, 1, 2, 2, 4} r = 2 Output : 4 Explanation: Any of the two 1s can be chosen as the first element, the second element can be any
15+ min read