当前位置:网站首页>Leetcode 1005 maximized array sum after K negations
Leetcode 1005 maximized array sum after K negations
2022-06-12 01:47:00 【baj001】
Ideas
- First step : The array from Sort small to large , So the minimum value is at the front
- The second step : Traverse back and forth , When you encounter a negative number, change it to a positive number , Judge this value ( minimum value ) The last number Is it smaller , If so, then idx++
- The third step : If K Greater than 0, that Repeatedly change the element with the lowest value , take K run out
- Step four : Sum up
class Solution {
public int largestSumAfterKNegations(int[] A, int K) {
if(A.length == 1) return K % 2 == 0 ? A[0] : -A[0];
Arrays.sort(A);
int sum = 0;
int idx = 0;
for(int i = 0; i < K; i++){
// Don't take the last position , Because the last position is the largest
if(i < A.length - 1 && A[idx] < 0){
A[idx] = -A[idx];
if(A[idx] >= Math.abs(A[idx + 1])) idx++;
// After jumping out of the loop , because idx already ++, Then enter again for when , The judgment is the next position
continue;
}
// If no value is found to be less than 0 Of course. , In order to achieve k Secondary inversion , Only the current value can be manipulated ( Invert the current value )
A[idx] = -A[idx];
}
// Statistics sum
for(int i = 0; i < A.length; i++){
sum += A[i];
}
return sum;
}
}
边栏推荐
- 如何让杀毒软件停止屏蔽某个网页?以GDATA为例
- Installing mysql-5.7 for Linux (centos7)
- [从零开始学习FPGA编程-20]:快速入门篇 - 操作步骤4-2-Altera Quartus II工具的快速使用(modelSim联合仿真、程序下载到Altera开发板)
- Prism框架初识-模块化介绍
- Websocket is closed after 10 seconds of background switching
- Google Ads 的优势
- Tiobe - programming language ranking in June 2022
- "It's safer to learn a skill!" The little brother of Hangzhou campus changes to software testing, and likes to mention 10k+ weekend!
- Perceptron from 0 to 1
- Huawei, this is too strong
猜你喜欢
随机推荐
Software engineering course: Chapter 2 software problem definition and feasibility analysis after class exercises
“還是學一門技術更保險!”杭州校區小哥哥轉行軟件測試,喜提10K+雙休!
lua 函数
Fatal error in launcher: unable to create process using
Subject knowledge and educational ability of information technology in the first half of 2019 – subjective questions
如何提高广告的广告评级,也就是质量得分?
“还是学一门技术更保险!”杭州校区小哥哥转行软件测试,喜提10K+双休!
博文推荐|BookKeeper - Apache Pulsar 高可用 / 强一致 / 低延迟的存储实现
PCA from 0 to 1
Simulated 100 questions and simulated examination for safety management personnel of metal and nonmetal mines (small open pit quarries) in 2022
2022 tool fitter (Advanced) recurrent training question bank and online simulation examination question bank source: YiDianTong official account of safety production simulation examination
初探性能优化!从2个月到4小时的性能提升!
Introduction to SVM
2022工具钳工(高级)复训题库及在线模拟考试题库来源:安全生产模拟考试一点通公众号
如何最大化的利用各种匹配方式? ——Google SEM
2022年金属非金属矿山(小型露天采石场)安全管理人员考试模拟100题及模拟考试
Simplified interpretation of accuracy and recall in AI papers
Linux(CentOS7)安裝MySQL-5.7版本
Prism框架初识-模块化介绍
商城开发知识点









