HackerRank Fair Rations Solution

İnanç Yılmaz
3 min readJun 9, 2022

--

Fair Rations challange in kotlin.

Today I will explain a question in HackerRank. I really liked the question. Just because of the solutions. It’s not a hard problem but the question wants to think over the solutions carefully. Let’s explain the question.

Question
You are the benevolent ruler of Rankhacker Castle, and today you’re distributing bread. Your subjects are in a line, and some of them already have some loaves. Times are hard and your castle’s food stocks are dwindling, so you must distribute as few loaves as possible according to the following rules:
Every time you give a loaf of bread to some person , you must also give a loaf of bread to the person immediately in front of or behind them in the line (i.e., i+ 1 person or i -1).
After all the bread is distributed, each person must have an even number of loaves. Given the number of loaves already held by each citizen, find and print the minimum number of loaves you must distribute to satisfy the two rules above. If this is not possible, print NO.

Example: When the line it’s like:
2 3 4 5 6
The initial distribution is,(2,3,4,5,6).The requirements can be met as follows:
Give 1 loaf of bread each to the second and third people so that the distribution becomes (2,4,5,5,6).
Give 1 loaf of bread each to the third and fourth people so that the distribution becomes (2,4,6,6,6).

Each of the N subjects has an even number of loaves after 4 loaves were distributed.

Solution:

Firstly you may think to create a loop and start to distribute the bread. But instead of this solution, we need to figure out, is there any solution for that line?

We’re mapping the list (solution of example) to an Odd-Even list. After then;
We’re counting the Odd Numbers. If the odd numbers count is odd, we can’t resolve the problem so return No.

So we eliminated the no solution lines.
After then, we need to find out the odd numbers Indexes. We’re going to calculate the bread count by getting the differences between them.

So we got differences in whole indexes between each other. That count is bread distribution times. When we doubled that we had distributed loaves of bread count.

I solved the harder questions than it though, now my favorite question is this.
Thank u for has been reading it.

--

--

İnanç Yılmaz
İnanç Yılmaz

Written by İnanç Yılmaz

Android Developer, Industrial Engineer

No responses yet