LeetCode Entry

1464. Maximum Product of Two Elements in an Array

12.12.2023 easy 2023 kotlin

#### Join me on Telegram

1464. Maximum Product of Two Elements in an Array easy blog post substack youtube image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/436

Intuition

We can sort, we can search twice for indices, we can scan once with two variables.

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code


  fun maxProduct(nums: IntArray): Int = with(nums.indices){
    maxBy { nums[it] }.let { i ->
    (nums[i] - 1) * (nums[filter { it != i }.maxBy { nums[it] }] - 1)
  }}