관리 메뉴

솜씨좋은장씨

[leetCode] 1464. Maximum Product of Two Elements in an Array (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 1464. Maximum Product of Two Elements in an Array (Python)

솜씨좋은장씨 2020. 12. 17. 00:06
728x90
반응형

Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).

 

Example 1:

Input: nums = [3,4,5,2]
Output: 12 
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.

Example 2:

Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3:

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

 

Constraints:

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

Solution

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        if len(nums) == 2:
            answer = (nums[0]-1) * (nums[1]-1)
        else:
            max_num = max(nums)
            nums.remove(max_num)
            sec_max_num = max(nums)
            
            answer = (max_num-1) * (sec_max_num-1)
            
        return answer

Solution 해설

이 문제는 입력 받은 리스트 안의 가장 큰 두 수의 각각 -1한 값을 곱을 구하는 문제입니다.

먼저 nums의 길이가 2이면 nums 안에 있는 두 개의 수가 가장 큰 두 수 이므로 바로 결과를 도출하고

그렇지 않으면 max를 활용하여 가장 큰 수를 먼저 찾고

해당 수를 리스트에서 remove로 지우고 다시 max를 활용하여 두번째 큰 수를 찾아 결과를 도출합니다.

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments