반응형
최댓값과 그다음 최댓값을 구하는 문제다.
class Solution {
public:
int maxProduct(vector<int>& nums) {
int max1=0; int location1=0;
int max2=0; int location2=0;
for(int i = 0; i<nums.size(); i++)
if(nums[i] > max1){
max1 = nums[i];
location1 = i;
}
for(int i = 0; i<nums.size(); i++)
if(nums[i] > max2 && i !=location1){
max2 = nums[i];
location2 = i;
}
return (max1-1)*(max2-1);
}
};
두 값이 같을 수도 있기 때문에 위치로 구별했다.
뭔가 더럽다.
정렬하고 앞에 두 개 하는 게 더 낫다.
class Solution {
public:
int maxProduct(vector<int>& nums) {
sort(nums.rbegin(), nums.rend());
return (nums[0]-1)*(nums[1]-1);
}
};
다른 코드도 봐야겠다.
반응형
'IT > 알고리즘' 카테고리의 다른 글
17] Leetcode 1323. Maximum 69 Number (0) | 2020.06.29 |
---|---|
16] Leetcode 1252. Cells with Odd Values in a Matrix (0) | 2020.06.27 |
14] Leetcode 1221. Split a String in Balanced Strings (0) | 2020.06.25 |
13] Leetcode 709. To Lower Case (0) | 2020.06.25 |
12] Leetcode 1486. XOR Operation in an Array (0) | 2020.06.24 |
댓글