122.买卖股票的最佳时机 II
简单题,每天都贪心即可
class Solution {public int maxProfit(int[] prices) {int sum = 0;for (int i = 1; i < prices.length; i++) sum += Math.max(prices[i]-prices[i-1],0);return sum;}
}
55. 跳跃游戏
记录能跳的最远范围,每次跳跃越远越好
代码中动态改变循环上界比较少见
class Solution {public boolean canJump(int[] nums) {if (nums.length == 1) return true;int range = 0;for (int i = 0; i <= range; i++) {range = Math.max(range,i+nums[i]);if (range >= nums.length-1) return true;}return false;}
}
45.跳跃游戏 II
i==cur的时候更新cur并进入下一次跳跃
class Solution {public int jump(int[] nums) {if (nums.length == 1 || nums.length == 0) return 0;int count = 0, cur = 0, max = 0;for (int i = 0; i < nums.length; i++) {max = Math.max(max,i+nums[i]);if (max >= nums.length-1) {count++;break;}if (i==cur){cur = max;count++;}}return count;}
}
1005.K次取反后最大化的数组和
每次都牺牲值最小的即可
class Solution {public int largestSumAfterKNegations(int[] nums, int k) {int sum = 0;Arrays.sort(nums);for(int i = 1;i <= k;i++){int temp = -nums[0];nums[0] = temp;Arrays.sort(nums);}for(int j = 0;j < nums.length;j++) sum += nums[j];return sum;}
}