LeetCode:1005.K次取反后最大化的数组和
1005. K 次取反后最大化的数组和 - 力扣(LeetCode)
1.思路
整体按照元素绝对值的大小进行排序,保证最大非负数先被赋予正值以保证整体和的最大值,之后遍历赋值,最后给最后的k进行尾部赋值
2.代码实现
1class Solution {
2 public int largestSumAfterKNegations(int[] nums, int k) {
3 // 排序
4 nums = IntStream.of(nums) // 数组转换为IntStream流
5 .boxed() // IntStream流转换为Stream流
6 .sorted((o1, o2) -> Math.abs(o2) - Math.abs(o1)) // 按照绝对值进行倒叙排序
7 .mapToInt(Integer::intValue).toArray(); // 使用.mapToInt(Integer::intValue)将排序后的Stream流转换回IntStream流
8 // 使用.toArray()将IntStream流转换为整数数组
9 // 赋值
10 int len = nums.length;
11 for (int i = 0; i < len; i++) {
12 if (nums[i] < 0 && k > 0) {
13 nums[i] = - nums[i];
14 k--;
15 }
16 }
17 // 遍历完之后,如果k值还没用完,则将尾部最小值进行赋值即可保证整体最大
18 if (k % 2 == 1) nums[len - 1] = -nums[len - 1];
19 // // 使用Arrays.stream将整数数组nums转换为IntStream流,并计算元素的总和
20 return Arrays.stream(nums).sum();
21 // 输出
22 }
23}
3.复杂度分析
时间复杂度:O(nlogn).
空间复杂度:O(1).
LeetCode:134. 加油站
1.思路
①暴力解法:超时
②贪心法:一层for循环,一个特殊节点,当前油量和<0时,index+1,也即从下一节点开始才有可能,总剩余油量为totalSum,决定了是否可以走完一圈。
2.代码实现
1// 暴力解法
2class Solution {
3 public int canCompleteCircuit(int[] gas, int[] cost) {
4 int n = gas.length;
5 //考虑从每一个点出发
6 for (int i = 0; i < n; i++) {
7 int j = i;
8 int remain = gas[i];
9 //当前剩余的油能否到达下一个点
10 while (remain - cost[j] >= 0) {
11 //减去花费的加上新的点的补给
12 remain = remain - cost[j] + gas[(j + 1) % n];
13 j = (j + 1) % n;
14 //j 回到了 i
15 if (j == i) {
16 return i;
17 }
18 }
19 }
20 //任何点都不可以
21 return -1;
22 }
23}
24// 时间复杂度:O(n^2).
25// 空间复杂度:O(1).
————————
1// 贪心法:
2class Solution {
3 public int canCompleteCircuit(int[] gas, int[] cost) {
4 int curSum = 0;
5 int totalSum = 0;
6 int index = 0;
7 for (int i = 0; i < gas.length; i++) {
8 curSum += gas[i] - cost[i];
9 totalSum += gas[i] - cost[i];
10
11 if (curSum < 0) {
12 index = (i + 1) % gas.length;
13 curSum = 0;
14 }
15 }
16 if (totalSum < 0) return -1;
17 return index;
18 }
19}
3.复杂度分析
时间复杂度:O(n)
空间复杂度:O(1)
LeetCode:135. 分发糖果
1.思路
前后分别双向遍历,首次遍历赋值,找出右>左,二次遍历找出左>右并选最大值。
2.代码实现
1class Solution {
2 public int candy(int[] ratings) {
3 int len = ratings.length;
4 int[] candyArray = new int[len];
5 candyArray[0] = 1;
6 for (int i = 1; i < len; i++) {
7 candyArray[i] = (ratings[i] > ratings[i - 1]) ? candyArray[i - 1] + 1 : 1;
8 }
9 for (int i = len - 2; i >= 0; i--) {
10 if (ratings[i] > ratings[i + 1]) {
11 candyArray[i] = Math.max(candyArray[i], candyArray[i + 1] + 1);
12 }
13 }
14 int result = 0;
15 for (int i = 0; i < candyArray.length; i++) {
16 result += candyArray[i];
17 }
18 return result;
19 }
20}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(n).