题解 | #最大放牛数# 贪心
最大放牛数
https://www.nowcoder.com/practice/5ccfbb41306c445fb3fd35a4d986f8b2
知识点
贪心
思路
贪心,从左到右优先填入可以填入1的位置,如果可以填完则可以不引发争斗,反之会引发争斗。
AC code(C++)
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pasture int整型vector
* @param n int整型
* @return bool布尔型
*/
bool canPlaceCows(vector<int>& pasture, int n) {
int m = pasture.size();
for (int i = 0; i < m and n > 0; i ++) {
if (pasture[i]) continue;
if (!i or pasture[i-1] == 0) {
pasture[i] = 1;
n --;
}
}
return !n;
}
};

