---
# System prepended metadata

title: Untitled

---

**1464. Maximum Product of Two Elements in an Array**

```
Example 1:
Input: nums = [3,4,5,2]
Output: 12 
Explanation: (4-1)*(5-1) = 3*4 = 12. 

Example 2:
Input: nums = [1,5,4,5]
Output: 16 
Explanation: (5-1)*(5-1) = 16.

Example 3:
Input: nums = [3,7]
Output: 12
```

解法一: 先使用qsort()排序由大到小，再取最前面兩個數相乘，O(NlogN)
(code 略)

解法二: 逐一掃瞄Array元素，紀錄最大值和次大值，O(N)

```c=
int maxProduct(int* nums, int numsSize){
    int largest = 1, second_largest = 1;

    for (int i = 0; i < numsSize; i++) {
        if (nums[i] > largest) {
            second_largest = largest;
            largest = nums[i];
        } else if (nums[i] > second_largest) {
            second_largest = nums[i];
        } else {
            // do nothing
        }        
    }

    return (largest - 1) * (second_largest - 1);
}
```


