Flip String to Monothone Increasing || Ruby || Easy to understand

Ruby; not very optimal by memory usage, but clear enough
Algorithm:

  • Accumulatively count number of 1s from the beginning of string to the current place in the string
  • Similarly count 0s from the end
  • Add number of 1s before to number of 0s after - this will give number of flips for every place in the string; and subtract 1 b/c we don't need to flip current one - it could be 0 or 1, it will not break monotonously b/c all before will be all 0s and all after will be all 1s
  • Find minimum of given running sum above
class Array
    def accum
        inject([]) {|r, v| r << yield(r.last, v) }
    end
end

def min_flips_mono_incr(s)
    ones = s.chars.accum {|l, v| [l, v.ord - '0'.ord].compact.sum }
    zeros = s.chars.reverse.accum {|l, v| [l, '1'.ord - v.ord].compact.sum }.reverse
    ones.zip(zeros).collect(&:sum).min - 1
end
Comments (1)