文章目录
- day27:贪心part1,基础篇
- 455.分发饼干
- 376.摆动序列
- 53.最大子数组和
day27:贪心part1,基础篇
455.分发饼干
循环结束条件注意饼干比孩子多的情况
class Solution {public int findContentChildren(int[] g, int[] s) {Arrays.sort(g);Arrays.sort(s);int ans = 0;// idx控制胃口,i控制饼干int idx = 0;for (int i = 0; i < s.length && idx < g.length; i++) {if (s[i] >= g[idx]) {idx++;ans++;}}return ans;}
}
376.摆动序列
关键在于如何区分上下坡平坡和同方向平坡的情况
class Solution {public int wiggleMaxLength(int[] nums) {if (nums.length == 1) return 1;// 理解为开始点左边有一个平坡,使得可以从第一个节点开始遍历逻辑int prediff = 0;int nextdiff = 0;// 默认最右边是峰值点int ans = 1;for (int i = 0; i < nums.length - 1; i++) {nextdiff = nums[i + 1] - nums[i];if ((prediff >= 0 && nextdiff < 0) || (prediff <= 0 && nextdiff > 0)) {ans++;prediff = nextdiff;}}return ans;}
}
53.最大子数组和
class Solution {public int maxSubArray(int[] nums) {int ans = Integer.MIN_VALUE;int sum = 0;for (int i = 0; i < nums.length; i++) {sum += nums[i];if (sum > ans) ans = sum;if (sum < 0) sum = 0;}return ans;}
}