455. Assign Cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.
题目解析:
- 贪心,按从大到小的顺序分
代码:
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
int si = s.length - 1, gi = g.length - 1;
while (si >= 0 && gi >= 0) {
if (s[si] >= g[gi]) {
si--;
gi--;
count++;
} else {
gi--;
}
}
return count;
}
}
376. Wiggle Subsequence
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
- For example,
[1, 7, 4, 9, 2, 5]is a wiggle sequence because the differences(6, -3, 5, -7, 3)alternate between positive and negative. - In contrast,
[1, 4, 7, 2, 5]and[1, 7, 4, 5, 5]are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array nums, return the length of the longest wiggle subsequence of nums.
题目解析:
- difference 可能是正数,负数或0
- 当前一个different和当前difference都为正或都为负是跳过
- 当前difference为0 也跳过
- 当前一个difference为0而当前difference不为0时+1
- 当前一个difference和当前difference 一个为正一个为负时+1
代码:
class Solution {
public int wiggleMaxLength(int[] nums) {
if (nums.length == 1) return 1;
int prevDiff = nums[1] - nums[0];
int max = prevDiff == 0 ? 1 : 2;
for (int i = 2; i < nums.length; i++) {
int diff = nums[i] - nums[i-1];
if (diff == 0 || diff * prevDiff > 0) continue;
else {
prevDiff = diff;
max++;
}
}
return max;
}
}
53. Maximum Subarray
Given an integer array nums, find the subarray with the largest sum, and return its sum.
题目解析:
- 如果和为负数,则从下一位开始从新开始
代码:
class Solution {
public int maxSubArray(int[] nums) {
int maxSum = Integer.MIN_VALUE;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
maxSum = sum > maxSum ? sum : maxSum;
if (sum < 0) {
sum = 0;
continue;
}
}
return maxSum;
}
}