当前位置: 首页 > news >正文

MaxProduct

public class MaxProduct {public static int maxProduct(int[] arr) {if (arr == null || arr.length < 2) {return 0;}int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;for (int num : arr) {if (num > max1) {max2 = max1;max1 = num;} else if (num > max2) {max2 = num;}if (num < min1) {min2 = min1;min1 = num;} else if (num < min2) {min2 = num;}}return Math.max(max1 * max2, min1 * min2);}
}

import org.junit.Test;
import static org.junit.Assert.*;public class MaxProductTest{@Testpublic void testMaxProduct1() {// 正数和负数混合int[] arr1 = {3, 5, -2, 8, -7};assertEquals(40, MaxProduct.maxProduct(arr1)); // 8*5}@Testpublic void testMaxProduct2() {// 全负数int[] arr2 = {-1, -4, -3, -2};assertEquals(12, MaxProduct.maxProduct(arr2)); // -4*-3}@Testpublic void testMaxProduct3() {// 全正数int[] arr3 = {1, 2, 3, 4};assertEquals(12, MaxProduct.maxProduct(arr3)); // 4*3}@Testpublic void testMaxProduct4() {// 只有一个元素int[] arr4 = {5};assertEquals(0, MaxProduct.maxProduct(arr4));}@Testpublic void testMaxProduct5() {// 空数组int[] arr5 = {};assertEquals(0, MaxProduct.maxProduct(arr5));}
}
http://www.gsyq.cn/news/17949.html

相关文章:

  • Lab 4 Challenge - Sum of Proper Elements
  • Ignite3 竟然变成分布式数据库了!
  • WCH低功耗蓝牙系列芯片usb烧录故障排查
  • 使用docker构建.net api镜像及nginx反向代理 - binzi
  • Docker实用篇(初识Docker,Docker的基本操作,Dockerfile自定义镜像,Docker-Compose,Docker镜像仓库) - a
  • C 语言的验证码图像识别系统实现
  • 一个有趣的网站,可以给自己生成一个奖牌:aitokenawards.com
  • 109
  • lzr 的区间(interval)
  • 使用c#操作elasticsearch8
  • 使用虚幻引擎|UE5制作自动开关门 - 教程
  • 计算机中级
  • CF45C Dancing Lessons 题解
  • APUE学习笔记之文件IO(三) - Invinc
  • 供应链优化技术助力应对疫情挑战
  • 搜索关键词 - 呓语
  • 阅读《构建之法》产生的问题
  • 每日反思(2025.10.09)
  • 软件工程学习日志2025.10.9
  • 骄傲 雨伞边缘处的暗槽 从最原初裂缝开凿 被碰触和温暖击倒 停止思考
  • webpack library - 指南
  • 被彼此笼罩 任回忆将我们缠绕 狂欢者戴上了镣铐 得益者撕裂了嘴角 吞下这毒药
  • QGIS导出TIF栅格图层
  • 20251009
  • 20232324 2025-2026-1 《网络与系统攻防技术》实验一实验报告
  • 汽车行业AI视觉检测方案(三):引领轮胎智检 - 实践
  • 利用旋钮控制小灯亮度
  • 已严肃完成今日96种状态的超级神仙DP大学习
  • P3388 【模板】割点(割顶) tarjan
  • 数据结构——受限线性表之栈 - 实践