title: Counting minimum number of swaps to group characters in string
body: <p>I'm trying to solve a pretty complex problem with strings:</p>
  
  <p>Given is a string with up to 100000 characters, consisting of only two different characters 'L' and 'R'. A sequence 'RL' is considered "bad", and such occurrences have to be reduced by applying swaps. </p>
  
  <p>However, the string is to be considered circular, so even the string 'LLLRRR' has an 'RL' sequence formed by the last 'R' and the first 'L'.</p>
  
  <p>Swaps of two consecutive elements can be made. So we can swap only elements that are on positions <em>i</em> and <em>i+1</em>, or on position 0 and <em>n-1</em>, if <em>n</em> is the length of the string (the string is 0-indexed).</p>
  
  <p>The goal is to find the minimum number of swaps needed to leave only one bad connection in the string.</p>
  
  <h3>Example</h3>
  
  <p>For the string 'RLLRRL' the problem can be solved with exactly one swap: swap the first and the last characters (since the string is circular). The string will thus become 'LLLRRR' with one bad connection.</p>
  
  <h3>What I tried</h3>
  
  <p>My idea is to use dynamical programming, and to calculate for any given 'L' how many swaps are needed to put all other 'L's left to that 'L', and, alternatively, to the right of this 'L'. For any 'R' I calculate the same.</p>
  
  <p>This algorithm works in <em>O(N)</em> time, but it doesn't give the correct result.</p>
  
  <p>It doesn't work when I have to swap the first and the last elements. What should I add to my algorithm to make it work also for those swaps?</p>