当所有元素都是偶数时,数组可以减少一半的最大次数
- 最后更新 : 2021年8月10日
给定一个数组arr,任务是在数组中所有元素都是偶数时对数组进行操作。在一次操作中,用 X/2替换数组中的每个整数 X。找到你能执行的最大可能的操作数。
例子。
输入: arr[] = {8, 12, 40}
输出。 2
解释。 最初,{8, 12, 40}存在于数组中。因为这些整数都是偶数,所以你可以进行操作。执行一次操作后,数组变成{4, 6, 20}。因为所有这些
,所以我们可以再次进行操作。操作两次后,数组变成{2, 3, 10}。现在,数组中出现了一个奇数 "3",所以不能再进行操作。
因此,最多可以进行两次操作。输入: arr[] = {5, 6, 8, 10}
输出: 0
解释。 因为初始数组中有一个奇数5,所以我们不能执行操作,甚至
一次。
办法。通 过一些简单的观察,可以解决给定的问题。
- 如果目前数组中的所有整数都是偶数,那么我们就把所有的数字除以2。
- 因此,问题简化为寻找一个元素arr[i]能被2除以的次数。答案是所有i的times[i]的最小值。
- 与其使用一个额外的数组times[],我们可以在每个阶段更新答案,只需保留一个变量,这就将空间复杂度降低到O(1),因为我们没有使用任何额外的空间。
下面是上述想法的实现。
C++
// C++ code implementation for the above approach#include <bits/stdc++.h>using namespace std;// Function to return the number// of operations possibleint arrayDivisionByTwo(int arr[],int n){// counter to store the number of times the// current element is divisible by 2int cnt = 0;// variable to store the final answerint ans = INT_MAX;for (int i = 0; i < n; i++) {// Initialize the counter to zero// for each elementcnt = 0;while (arr[i] % 2 == 0) {// update the counter till the// number is divisible by 2arr[i] = arr[i] / 2;cnt++;}// update the answer as// the minimum of all the countsans = min(ans, cnt);}return ans;}// Driver codeint main(){int arr[] = { 8, 12, 40 };int n =sizeof(arr) /sizeof(arr[0]);cout << arrayDivisionByTwo(arr, n);return 0;} |
输出。
2
**时间复杂度。**O(32 * n)
空间复杂度。 O(1)
读者请注意!现在不要停止学习。以学生可接受的价格获得所有重要的DSA概念。 DSA自学课程以适合学生的价格掌握所有重要的DSA概念,并为行业做好准备。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
如果你想参加专家的现场课程 ,请参考 面向在职人士的DSA现场课程 和 面向学生的竞争性编程直播课程.
我的个人笔记 arrow_drop_up
保存