C++ Program to find maximal achievable diversity of music notes

Suppose we have a string S with n elements. Amal's song consists of n notes, which we will treat as positive integers. The diversity of a song is the number of different notes it contains. We want to make it more diverse. We cannot arbitrarily change the song. Instead, for each of the n notes in the song, she can either leave it as it is or increase it by 1. Given sequence is a song where integer is describing the notes, we have to find out the maximal, achievable diversity.

Problem Category

The above-mentioned problem can be solved by applying Greedy problem-solving techniques. The greedy algorithm techniques are types of algorithms where the current best solution is chosen instead of going through all possible solutions. Greedy algorithm techniques are also used to solve optimization problems, like its bigger brother dynamic programming. In dynamic programming, it is necessary to go through all possible subproblems to find out the optimal solution, but there is a drawback of it; that it takes more time and space. So, in various scenarios greedy technique is used to find out an optimal solution to a problem. Though it does not gives an optimal solution in all cases, if designed carefully it can yield a solution faster than a dynamic programming problem. Greedy techniques provide a locally optimal solution to an optimization problem. Examples of this technique include Kruskal's and Prim's Minimal Spanning Tree (MST) algorithm, Huffman Tree coding, Dijkstra's Single Source Shortest Path problem, etc.



So, if the input of our problem is like A = [1, 2, 2, 2, 5, 6], then the output will be 5, because we can increase the second, fifth and sixth element to obtain the sequence 1, 3, 2, 2, 6, 7, which has 5 different elements.


To solve this, we will follow these steps −

n := size of A
Define one set s
for initialize i := 0, when i < n, update (increase i by 1), do:
   x := A[i]
   if x is in s, then:
      (increase x by 1)
   insert x into s
return size of s


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   int n = A.size();
   set<int> s;
   for (int i = 0; i < n; i++){
      int x = A[i];
      if (s.count(x))
   return s.size();
int main(){
   vector<int> A = { 1, 2, 2, 2, 5, 6 };
   cout << solve(A) << endl;


{ 1, 2, 2, 2, 5, 6 }