We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Practice
  • Certification
  • Compete
  • Career Fair
  • Hiring developers?
  1. Practice
  2. Algorithms
  3. Sorting
  4. Lily's Homework
  5. Discussions

Lily's Homework

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • devinludwig 3 years ago+ 0 comments

    This approach in Ruby:

    n = gets.to_i
    a = gets.strip.split.map &:to_i
    def find_swaps(a)
        map = a.each_with_index.map{|x,i| [x,i]}.to_h
        swaps = 0; sort = a.sort
        for i in 0...a.size do
            if sort[i] != a[i]
                swaps += 1
                map[a[i]] = map[sort[i]]
                a[map[sort[i]]], a[i] = a[i], sort[i] end end
        swaps end
    puts [find_swaps(Marshal.load(Marshal.dump(a))),find_swaps(a.reverse)].min
    
    1|
    ParentPermalink
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature