Find time taken for signal to reach all positions in a string in C++


In this tutorial, we will be discussing a program to find time taken for signal to reach all positions in a string

For this we will be provided with a string containing ‘x’ and ‘o’. A signal originates from ‘x’ and travels in both directions changing one ‘o’ value in one unit time. Our task is to calculate the complete time to convert whole string into ‘x’s.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//calculating the total required time
int findMaximumDuration(string s, int n) {
   int right = 0, left = 0;
   int count = 0, maximumLength = INT_MIN;
   s = s + '1';
   for (int i = 0; i <= n; i++) {
      if (s[i] == 'o')
         count++;
      else {
         if (count > maximumLength) {
            right = 0;
            left = 0;
            if (s[i] == 'x')
               right = 1;
            if (((i - count) > 0) && (s[i - count - 1] == 'x'))
               left = 1;
            count = ceil((double)count / (right + left));
            maximumLength = max(maximumLength, count);
         }
         count = 0;
      }
   }
   return maximumLength;
}
int main() {
   string str = "xooxoooxxoooxoooxooxooox";
   int length = str.size();
   cout << findMaximumDuration(str, length);
   return 0;
}

Output

2

Updated on: 19-Aug-2020

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements