今日任务
55. 跳跃游戏
45.跳跃游戏 II
1005.K次取反后最大化的数组和
55. 跳跃游戏
题目链接: . - 力扣(LeetCode)
class Solution {
public int maxSubArray(int[] nums) {
int sum = 0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
max = Math.max(max,sum);
if (sum <= 0) {
sum = 0;
}
}
return max;
}
}
45.跳跃游戏 II
题目链接:. - 力扣(LeetCode)
class Solution {
public int jump(int[] nums) {
if (nums.length == 1) return 0;
int curDistance = 0;
int nextDistance = 0;
int res = 0;
for (int i = 0; i < nums.length; i++) {
nextDistance = Math.max(i + nums[i],nextDistance);
if (i == curDistance) {
res++;
curDistance = nextDistance;
if (nextDistance >= nums.length - 1) {
break;
}
}
}
return res;
}
}
1005.K次取反后最大化的数组和
题目链接: . - 力扣(LeetCode)
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue();
for (int i = 0; i < nums.length; i++) {
queue.offer(nums[i]);
}
while (!queue.isEmpty()) {
int tmp = queue.peek();
if (tmp < 0 && k > 0) {
k--;
queue.poll();
queue.offer(-tmp);
} else {
break;
}
}
if (k % 2 == 1) {
int tmp = queue.poll();
queue.offer(-tmp);
}
int res = 0;
while (!queue.isEmpty()) {
res += queue.poll();
}
return res;
}
}