My LeetCode Diary - Day30 Greedy Algo
455. Assign Cookies
Link
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
//考虑大胃口
int index = s.length - 1;
for (int i = g.length -1 ;i >=0; i--) {
if (index >= 0 && g[i] <= s[index]){
index--;
count++;
}
}
return count;
}
}
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int start = 0;
int count = 0;
//考虑小胃口
for (int i = 0; i < s.length && start < g.length; i++) {
if (s[i] >= g[start]) {
start++;
count++;
}
}
return count;
}
}
376. Wiggle Subsequence
Link
class Solution {
public int wiggleMaxLength(int[] nums) {
if (nums.length <= 1) {
return nums.length;
}
int curDiff = 0;
int preDiff = 0;
int count = 1;
for (int i = 1; i < nums.length; i++) {
curDiff = nums[i] - nums[i-1];
if ((curDiff>0 && preDiff <= 0) || (curDiff<0 && preDiff >=0)) {
count++;
preDiff = curDiff;
}
}
return count;
}
}
53. Maximum Subarray
Link
class Solution {
public int maxSubArray(int[] nums) {
if (nums.length == 1) {
return nums[0];
}
int sum = Integer.MIN_VALUE;
int count = 0;
for (int i = 0; i < nums.length; i++) {
count += nums[i];
sum = Math.max(sum,count);
if (count <= 0) {
count = 0;
}
}
return sum;
}
}