File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -249,6 +249,29 @@ class Solution {
249249 }
250250}
251251```
252+ ```
253+ // 解法3
254+ class Solution {
255+ public int canCompleteCircuit(int[] gas, int[] cost) {
256+ int tank = 0; // 当前油量
257+ int totalGas = 0; // 总加油量
258+ int totalCost = 0; // 总油耗
259+ int start = 0; // 起点
260+ for (int i = 0; i < gas.length; i++) {
261+ totalGas += gas[i];
262+ totalCost += cost[i];
263+
264+ tank += gas[i] - cost[i];
265+ if (tank < 0) { // tank 变为负数 意味着 从0到i之间出发都不能顺利环路一周,因为在此i点必会没油
266+ tank = 0; // reset tank,类似于题目53.最大子树和reset sum
267+ start = i + 1; // 起点变为i点往后一位
268+ }
269+ }
270+ if (totalCost > totalGas) return -1;
271+ return start;
272+ }
273+ }
274+ ```
252275
253276### Python
254277暴力法
Original file line number Diff line number Diff line change @@ -128,6 +128,36 @@ class Solution {
128128
129129 }
130130}
131+
132+ // 版本二:排序数组并贪心地尽可能将负数翻转为正数,再根据剩余的k值调整最小元素的符号,从而最大化数组的总和。
133+ class Solution {
134+ public int largestSumAfterKNegations(int[] nums, int k) {
135+ if (nums.length == 1) return nums[0];
136+
137+ // 排序:先把负数处理了
138+ Arrays.sort(nums);
139+
140+ for (int i = 0; i < nums.length && k > 0; i++) { // 贪心点, 通过负转正, 消耗尽可能多的k
141+ if (nums[i] < 0) {
142+ nums[i] = -nums[i];
143+ k--;
144+ }
145+ }
146+
147+ // 退出循环, k > 0 || k < 0 (k消耗完了不用讨论)
148+ if (k % 2 == 1) { // k > 0 && k is odd:对于负数:负-正-负-正
149+ Arrays.sort(nums); // 再次排序得到剩余的负数,或者最小的正数
150+ nums[0] = -nums[0];
151+ }
152+ // k > 0 && k is even,flip数字不会产生影响: 对于负数: 负-正-负;对于正数:正-负-正
153+
154+ int sum = 0;
155+ for (int num : nums) { // 计算最大和
156+ sum += num;
157+ }
158+ return sum;
159+ }
160+ }
131161```
132162
133163### Python
You can’t perform that action at this time.
0 commit comments