贪心的本质是选择每一阶段的局部最优,从而达到全局最优。
455. 分发饼干
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
int sIndex = s.length - 1;
for (int i = g.length - 1; i >= 0; i--) {
if (sIndex >= 0 && g[i] <= s[sIndex]) {
count++;
sIndex--;
}
}
return count;
}
}
376.摆动序列
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. 最大子数组和
class Solution {
public int maxSubArray(int[] nums) {
if (nums.length == 1) {
return nums[0];
}
int sum = Integer.MIN_VALUE;
int temp = 0;
for (int i = 0; i < nums.length; i++) {
temp += nums[i];
sum = Math.max(sum, temp);
if (temp < 0) {
temp = 0;
}
}
return sum;
}
}
122. 买卖股票的最佳时机 II
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
for (int i = 1; i < prices.length; i++) {
result += Math.max(prices[i] - prices[i - 1], 0);
}
return result;
}
}
55. 跳跃游戏
class Solution {
public boolean canJump(int[] nums) {
if (nums.length == 1) {
return true;
}
int cover = 0;
for (int i = 0; i <= cover; i++) {
cover = Math.max(cover, i + nums[i]);
if (cover >= nums.length - 1) {
return true;
}
}
return false;
}
}
45. 跳跃游戏 II
class Solution {
public int jump(int[] nums) {
if (nums == null || nums.length == 0 || nums.length == 1) {
return 0;
}
int count = 0;
int curDistance = 0;
int nextDistance = 0;
for (int i = 0; i < nums.length; i++) {
nextDistance = Math.max(nextDistance, i + nums[i]);
if (nextDistance >= nums.length - 1) {
count++;
break;
}
if (i == curDistance) {
curDistance = nextDistance;
count++;
}
}
return count;
}
}
1005. K 次取反后最大化的数组和
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
List<Integer> list = new ArrayList<>();
for (int num : nums) {
list.add(num);
}
list.sort((a, b) -> Math.abs(a) - Math.abs(b));
int sum = 0;
for (int i = list.size() - 1; i >= 0; i--) {
if (k > 0 && list.get(i) < 0) {
list.set(i, -list.get(i));
k--;
}
}
if (k % 2 == 1) {
list.set(0, -list.get(0));
}
for (int num : list) {
sum += num;
}
return sum;
}
}
763. 划分字母区间
class Solution {
public List<Integer> partitionLabels(String s) {
int[] last = new int[26];
int length = s.length();
for (int i = 0; i < length; i++) {
last[s.charAt(i) - 'a'] = i;
}
List<Integer> partition = new ArrayList<>();
int start = 0, end = 0;
for (int i = 0; i < length; i++) {
end = Math.max(end, last[s.charAt(i) - 'a']);
if (i == end) {
partition.add(end - start + 1);
start = end + 1;
}
}
return partition;
}
}