C++ code to find out number of battery combos

C++Server Side ProgrammingProgramming

Suppose, we have n batteries that can be used a maximum of 5 times. We have some devices that need three batteries and each usage of the device increases the usage count of the batteries by 1. If we have to use the devices k times, we have to find out how many battery combinations we can make to power the devices. A battery cannot be used in two devices simultaneously and a battery that has been used 5 times cannot be included. The usage count of the batteries is given in the array batt.

So, if the input is like n = 6, k = 2, batt = {2, 4, 4, 2, 1, 3}, then the output will be 1.

There can be only one battery combination made to power devices for k times.

Steps

To solve this, we will follow these steps −

ans := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   if batt[i] + k <= 5, then:
      (increase ans by 1)
return ans / 3

Example

Let us see the following implementation to get better understanding

#include <bits/stdc++.h>
using namespace std;
#define N 100
int solve(int n, int k, int batt[]) {
   int ans = 0;
   for(int i = 0; i < n; i++){
      if(batt[i] + k <= 5)
         ans++;
   }
   return ans / 3;
}
int main() {
   int n = 6, k = 2, batt[] = {2, 4, 4, 2, 1, 3};
   cout<< solve(n, k, batt);
   return 0;
}

Input

6, 2, {2, 4, 4, 2, 1, 3}

Output

1
raja
Updated on 11-Mar-2022 05:45:04

Advertisements