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:
1.Every time you give a loaf of bread to some person I, you must also give a loaf of bread to the person immediately in front of or behind them in the line (i.e., persons i+1 or i-1).
2.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
1.Every time you give a loaf of bread to some person I, you must also give a loaf of bread to the person immediately in front of or behind them in the line (i.e., persons i+1 or i-1).
2.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:
Input: n=5, arr[]={2,3,4,5,6}
Output: 4
Approach
Java
public class FairRations {public static void main(String[] args) {int arr[] = { 2, 3, 4, 5, 6 };System.out.println(fairRations(arr));}static String fairRations(int[] arr) {int sum = 0;int n = arr.length;for (int i = 0; i < n; i++) {sum += arr[i];}int i = 0, cnt = 0;if (sum % 2 == 1) {return "NO";} else {while (i < n) {if (arr[i] % 2 == 1) {arr[i] += 1;arr[i + 1] += 1;i++;cnt += 2;} elsei++;}return ""+cnt;}}}
C++
#include <bits/stdc++.h>using namespace std;int main(){int n = 5;int arr[n] = {2, 3, 4, 5, 6}, sum = 0;for (int i = 0; i < n; i++){sum += arr[i];}int i = 0, cnt = 0;if (sum & 1){cout << "NO\n";}else{while (i < n){if (arr[i] & 1){arr[i] += 1;arr[i + 1] += 1;i++;cnt += 2;}elsei++;}cout << cnt << "\n";}return 0;}
No comments:
Post a Comment