LeetCode 1464. 数组中两元素的最大乘积

谁借莪1个温暖的怀抱¢ 2023-01-06 15:57 211阅读 0赞

给你一个整数数组 nums,请你选择数组的两个不同下标 i 和 j,使 (nums[i]-1)*(nums[j]-1) 取得最大值。

请你计算并返回该式的最大值。

2 <= nums.length <= 500
1 <= nums[i] <= 10^3

遍历找出数组中的最大值和次最大值即可:

  1. class Solution {
  2. public:
  3. int maxProduct(vector<int>& nums) {
  4. int i = 0, j = 0; // i是最大值,j是次大值
  5. for (int num : nums) {
  6. if (num > i) {
  7. j = i; // 当前最大值变为次大值
  8. i = num;
  9. } else if (num > j) {
  10. j = num;
  11. }
  12. }
  13. return (i - 1) * (j - 1);
  14. }
  15. };

发表评论

表情:
评论列表 (有 0 条评论,211人围观)

还没有评论,来说两句吧...

相关阅读