文章目录
- 1005.K次取反后最大化的数组和
- 贪心思路:
- 代码:
- 34. 加油站
- 思路一:全局贪心
- 代码:
- 思路二:
- 代码:
- 135. 分发糖果
- 思路:两边考虑
- 代码:
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]=-nums[i];k--;}}Arrays.sort(nums);if(k%2==1){nums[0]*=-1;}int res=0;for(int num:nums){res+=num;}return res;}
}
34. 加油站
思路一:全局贪心
代码:
class Solution {public int canCompleteCircuit(int[] gas, int[] cost) {int sum = 0;int min = 0;for (int i = 0; i < gas.length; i++) {sum += (gas[i] - cost[i]);min = Math.min(sum, min);//先获得最小值}// -2 -2+-2=-4 -2+-4=-6 3+-6=-3 3+-3=0if (sum < 0) return -1;if (min >= 0) return 0;for(int i=gas.length-1;i>=0;i--){int rest = gas[i] - cost[i];min += rest;//-6从后向前加if(min>=0)return i;}return 0;}
}
思路二:
代码:
class Solution {public int canCompleteCircuit(int[] gas, int[] cost) {int curSum = 0;//记录,判断区间是否可以跳过int totalSum = 0;//记录是否能走完一个循环int start = 0;// 记录开始位置for (int i = 0; i < gas.length; i++) {curSum+=gas[i] - cost[i];totalSum += (gas[i] - cost[i]);if(curSum<0){curSum=0;start=i+1;}}if(totalSum<0)return -1;return start;}
}
135. 分发糖果
思路:两边考虑
代码:
class Solution {public int candy(int[] ratings) {int len = ratings.length;int[] candyVec = new int[len];candyVec[0]=1;for(int i=1;i<ratings.length;i++){candyVec[i]=ratings[i]>ratings[i-1]?candyVec[i-1]+1:1;}for(int i=len-2;i>=0;i--){// candyVec[i]=ratings[i]>ratings[i+1]?Math.max(candyVec[i+1]+1,candyVec[i]):candyVec[i];if (ratings[i] > ratings[i + 1]) {candyVec[i] = Math.max(candyVec[i], candyVec[i + 1] + 1);}}int ans = 0;for (int num : candyVec) {ans += num;}return ans;}
}