https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/description/
This question can be solved greedily:
1): if there is one element is odd, we need to reduce 1 to make it even;
2): when all even, we can divide it by 2
Since 2) is always faster than 1, so we need to do operation 2) whenever it is possible.
See the code below:
class Solution {
public:
int minOperations(vector<int>& nums) {
int res = 0;
bool largerThan0 = true, allEven = true;
while(largerThan0) {
largerThan0 = false;
allEven = true;
for(auto &a : nums) {
if(a>0) largerThan0 = true;
if(a&1) {
--a;
++res;
allEven = false;
}
}
if(largerThan0 && allEven) {
for(auto &a : nums) a /= 2;
++res;
largerThan0 = true;
}
}
return res;
}
};
No comments:
Post a Comment