Mô tả bài toán
Cho mảng số nguyên, tìm 3 số có tích lớn nhất.
Ví dụ: [1,1,2,3,3] → 3 số: [2,3,3] → Tích = 18.
Giải pháp (Sắp xếp + So sánh 2 trường hợp)
- Sắp xếp mảng.
- Tích lớn nhất = max(
3 số lớn nhất,2 số nhỏ nhất (âm) × số lớn nhất). - Vì 2 số âm nhân nhau thành dương, có thể tạo tích lớn.
Ví dụ minh họa
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
int l = nums.size();
int a = nums[l-1], b = nums[l-2], c = nums[l-3];
int d = nums[0], e = nums[1];
return max(a * b * c, d * e * a);
}
};
int main() {
Solution ob;
vector<int> v = {1,1,2,3,3};
cout << ob.maximumProduct(v);
return 0;
}
Đầu vào
{1,1,2,3,3}
Đầu ra
18