You are given two arrays and . In each step, you can set if . Determine the minimum number of steps that are required to make all 's equal.
Example:
Input: n = 5, a[n] = {5, 7, 10, 5, 15}, b[n] = {2, 2, 1, 3, 5};
Output: 8
Approach
C++
#include <iostream>using namespace std;void numberOfSteps(int n, int a[], int b[]){int min = 5000;bool flag = false;int steps;for (int i = 0; i < n; i++){if (a[i] < min)min = a[i];}for (int i = 0; i < n; i++){while (a[i] > min){a[i] -= b[i];steps++;if (a[i] < 0){flag = true;break;}}if (flag)break;if (a[i] < min)min = a[i];}for (int i = 1; i < n; i++){if (a[i] != a[i - 1])flag = true;}if (flag)cout << "-1";elsecout << steps;}int main(){int n = 5;int a[n] = {5, 7, 10, 5, 15};int b[n] = {2, 2, 1, 3, 5};numberOfSteps(n, a, b);return 0;}
No comments:
Post a Comment