当前位置: 首页 > 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.jsqmd.com/news/10827/

相关文章:

  • 雪落 - L
  • PluginMonitor - Typecho 插件监控工具
  • STM32 教程
  • LibreChat-图文并茂手把手教你搭建自己的AI机器人 Step-by-step guide to building your own chatbot
  • Ignite3 竟然变成分布式数据库了!
  • NUIST 《程序设计基础》 实验1
  • [MIT 6.828] Lab 1 C, Assembly, Tools, and Bootstrapping
  • WCH低功耗蓝牙系列芯片usb烧录故障排查
  • 使用docker构建.net api镜像及nginx反向代理 - binzi
  • 利用sprintf与snprintf巧妙实现数值变量转换为字符串型
  • Helmholtz-Gibbs自由能与熵弹性
  • 日志|电话号码的字母组合|子集|回溯
  • Docker实用篇(初识Docker,Docker的基本操作,Dockerfile自定义镜像,Docker-Compose,Docker镜像仓库) - a
  • ROIR 2023
  • 【题解】P12992 [GCJ 2022 #1C] Intranets
  • ysyx:pa3.1批处理系统
  • 基于 C 语言的验证码图像识别系统实现
  • oppoR9m刷Linux系统: 引导知识
  • JAVA: Mybatis添加xml执行多行更新语句时报错
  • 安装Docker(CentOS安装Docker,CentOS7安装DockerCompose,Docker镜像仓库) - a
  • 一个有趣的网站,可以给自己生成一个奖牌:aitokenawards.com
  • 109
  • 20232416 2025-2026-1《网络与系统攻防技术》实验一实验报告
  • day008
  • lzr 的区间(interval)
  • IRB-120机械臂socket通信接受上位机指令运行程序段
  • 1.1.1.1 金融市场的定义与功能
  • 使用c#操作elasticsearch8
  • APUE学习笔记之文件IO(三) - Invinc
  • tornado异步操作数据库-mysql