본문 바로가기
IT/알고리즘

15] Leetcode 1464. Maximum Product of Two Elements in an Array

by 깻잎쌈 2020. 6. 25.
반응형
 

Maximum Product of Two Elements in an Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

최댓값과 그다음 최댓값을 구하는 문제다.

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);
    }
};

다른 코드도 봐야겠다.

반응형

댓글