Money Collection

Mr.savani is collecting a money from n students for a trip,  like collect $1 from 1st student, $3 from 3rd student and so on.. but it should not include k (unlucky number) into sum. if it includes k into sum, then ignore that student

 

Example:

n = number of student, k = unlucky number
i/p: 2,2, o/p: 3,
i/p: 3,3, o/p: 5, (could be 4 as well but find max sum)

Solution: Using Discriminant maths  D = b2 – 4ac

def maxMoney(n, k)
    sum = (n * (n + 1)) / 2
    sum -= 1 if Math.sqrt(1+8*k) % 1 == 0
    return sum
end

puts maxMoney(2,2)   # o/p 3
puts maxMoney(2,1)   # o/p 2
puts maxMoney(3,3)   # o/p 5
puts maxMoney(2000000000,4000000000000000)

Segregate 0s and 1s in an array

You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Traverse array only once.

Input array   =  [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] 
Output array =  [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

Solution:

def solution(arr)
  left = 0
  right = arr.length - 1

  while left < right do
    while (arr[left] == 0 && left < right) do
      left += 1
    end

    while (arr[right] == 1 && left < right) do
      right -= 1
    end

    if (left < right)
      arr[left] = 0
      arr[right] = 1
      left += 1
      right -= 1
    end
  end
  return arr
end

arr = [0,1,0,1,1,1,0,0,0]
print solution(arr)