4

#yyds干货盘点# 名企真题专题:最大乘积

 1 year ago
source link: https://blog.51cto.com/u_15488507/5916447
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# 名企真题专题:最大乘积

精选 原创

97的风 2022-12-06 18:09:05 博主文章分类:面试题 ©著作权

文章标签 System 空间复杂度 java 文章分类 Java 编程语言 阅读数230

1.简述:

描述

给定一个无序数组,包含正数、负数和0,要求从中找出3个数的乘积,使得乘积最大,要求时间复杂度:O(n),空间复杂度:O(1)

输入描述:

输入共2行,第一行包括一个整数n,表示数组长度 第二行为n个以空格隔开的整数,分别为A1,A2, … ,An

输出描述:

满足条件的最大乘积

示例1
4
3 4 1 2

2.代码实现:

import java.util.*;

class Main{
public static void main(String[] args) {
PDD1();
}
public static void PDD1(){
long sum = 1;
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
List<Long> arrayList = new ArrayList<>();
for (int i = 0; i < n; i++) {
arrayList.add(scanner.nextLong());
}
arrayList.sort((o1, o2) -> {
Long tmp = o2-o1;
return tmp.intValue();
}
);
if (arrayList.get(1)*arrayList.get(2)<arrayList.get(arrayList.size()-1)*arrayList.get(arrayList.size()-2)){
sum = arrayList.get(0)*arrayList.get(arrayList.size()-1)*arrayList.get(arrayList.size()-2);
}else {
sum = arrayList.get(0)*arrayList.get(1)*arrayList.get(2);
}
System.out.println(sum);
}

}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK