122、买卖股票的最佳时机
思路:记录当天和前一天的波动是正还是负数,将所有正数收集起来即可。
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for(int i = 1; i < prices.length; i++){
int wave = prices[i] - prices[i-1];
if(wave > 0) res += wave;
}
return res;
}
}
55、跳跃游戏
class Solution {
/*
public boolean canJump(int[] nums) {
int[] use = new int[nums.length];
use[0] = 1;
for(int i = 0; i < nums.length; i++){
if(use[i] == 1){
int temp = nums[i];
for(int j = i+1; j <= temp + i && j < use.length; j++){
use[j] = 1;
}
}else{return false;}
}
return true;
}
*/
public boolean canJump(int[] nums){
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、跳跃游戏2
思路:更新每一步的覆盖范围,一旦覆盖范围超过数组长度,就说明下一步一定能到。
如果当前范围走到头了还到,就进入下一步的覆盖范围
class Solution {
public int jump(int[] nums) {
if(nums == null || nums.length == 0 ||nums.length == 1){
return 0;
}
int curPool = 0;
int maxPool = 0;
int count = 0;
for(int i = 0; i < nums.length; i++){
maxPool = Math.max(maxPool, i + nums[i]);
if(maxPool >= nums.length - 1){
return count + 1;
}
if( i == curPool){
count++;
curPool = maxPool;
}
}
return count;
}
}
1005.K次取反后最大化的数组和
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
Arrays.sort(nums);
for(int i = 0 ; i < nums.length; i++){
if(nums[i] < 0 && k > 0){
nums[i] *= -1;
k--;
}else{break;}
}
Arrays.sort(nums);
if(k % 2 == 1){
nums[0] *= -1;
}
int sum = 0;
for(int i = 0;i < nums.length; i++){
sum += nums[i];
}
return sum;
}
}