和力扣的682题目一样。
但是输入的值范围不同。
LC是-1000 <= nums[i] <= 1000
NC是-10000<=A[i]<=10000
因此NC上用java的话会有溢出的可能~
方法1:java
先排序~
3种可能,数组全正、全负、有正有负。
全正、全负: long)A[n]*A[n-1]*A[n-2]
有正有负:(long)A[0]*A[1]*A[n])
import java.util.*;
public class Solution {
/**
* 最大乘积
* @param A int整型一维数组
* @return long长整型
*/
public long solve (int[] A) {
// write code here
Arrays.sort(A);
int n=A.length-1;
System.out.println(A[n]*A[n-1]*A[n-2]);
//有溢出需要强制转换
return Math.max((long)A[n]*A[n-1]*A[n-2],(long)A[0]*A[1]*A[n]);
}
}
方法2:python
class Solution:
def solve(self , A ):
# write code here
A.sort()
n=len(A)-1
return max(A[n]*A[n-1]*A[n-2], A[0]*A[1]*A[n])