In: Computer Science
Please write code in C++ and include all header files used not bits/stdc:
(Same number subsequence)
Write an O(n) program that prompts the user to enter a sequence of integers ending with 0 and finds longest subsequence with the same number.
Sample Run
Enter a series of numbers ending with 0: 2 4 4 8 8 8 8 2 4 4 0 The longest same number sequence starts at index 3 with 4 values of 8
The C++ code for the above problem is:
#include <iostream> 
using namespace std; 
int main() 
{
        double num, num_past;
        cout << "Enter a series of numbers ending with 0: ";
        cin >> num; // input number
        num_past = num;
        double val = num; // maximum number of repitions of a number
        int max_ind = 0, ind = 0; // index with maximum number of repitions of a number initialised to 0
        int max_rep = 1, rep = 0; // maximum number of repitions of a number initialised to 1
        while(num != 0) { // loop continues till 0 is not entered
                cin >> num;
                if(num_past != num) { // if new entered number is not equal to past number
                        if(max_rep < rep) {
                                max_rep = rep;
                                max_ind = ind;
                                val = num_past;
                        }
                        num_past = num; rep = 0;
                }
                rep++; ind++;
        }
        cout << "The longest same number sequence starts at index "<< max_ind - max_rep + 1 <<
                " with " << max_rep << " values of " << val; // display the required output
        return 0; 
} 
The sample of the code is:
The output sample of the code is:

The complexity of the above problem is O(n). Comment down if you have queries regarding the code.