MaximumProductofThreeNumbers
来源:互联网 发布:网络机柜的作用 编辑:程序博客网 时间:2024/05/22 02:12
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]Output: 6
Example 2:
Input: [1,2,3,4]Output: 24
Note:
- The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
- Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
题目是要求一个数组中任意三个数的最大乘积,但是并不是要找出三个最大的数这么简单的。因为数组
中是可能存在负数的,会出现两负一正乘积仍然为正的情况。比较出max1*max2*max3与min1*min2*max1中较大
的数返回即可。
public int maximumProduct(int[] nums) { int max1 = Integer.MIN_VALUE; int max2 = Integer.MIN_VALUE; int max3 = Integer.MIN_VALUE; int min1 = Integer.MAX_VALUE; int min2 = Integer.MAX_VALUE; for(int i=0; i<nums.length; i++) { if(nums[i] > max1) { max3 = max2; max2 = max1; max1 = nums[i]; } else if(nums[i] > max2) { max3 = max2; max2 = nums[i]; } else if(nums[i] > max3) { max3 = nums[i]; } if(nums[i] < min1) { min2 = min1; min1 = nums[i]; } else if(nums[i] < min2) { min2 = nums[i]; } } if(max2*max3 > min1*min2) { return max2*max3*max1; } return min1*min2*max1; }
阅读全文
0 0
- MaximumProductofThreeNumbers
- 【Ex.】通讯录的增删查改清空以及排序操作的实现
- 排序
- idea上SpringBoot 热部署 1.5.3RELEASE
- uva 315 Network
- 记录最近使用的jsp小技巧
- MaximumProductofThreeNumbers
- Spark Partition
- hdu2191(多重背包的二进制和普通做法)
- Codeforces 830D [DP]
- Python中json数据转换问题
- Java知识:TreeSet详解
- Intelij idea 集成scrapy开发环境
- tomcat 启动后 闪退 (环境配置都是对的TT)
- 专注要事、把手弄脏、高效优雅是对抗规模化焦虑的好办法--读Getting Real(达成现实)和 Rework(重塑工作)