Leetcode # 1502. Can Make Arithmetic Progression From Sequence

https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence

Solution

Time Complexity: O(n)
Space Complexity: O(n)
(The input and output generally do not count towards the space complexity.)

class Solution:
  def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
    min_n = max_n = arr[0]
    all_n = set()
    for n in arr:
      min_n = min(min_n, n)
      max_n = max(max_n, n)
      all_n.add(n)

    if len(all_n) == 1:
      return True

    dif = (max_n - min_n) / (len(arr) - 1)
    cur_n = min_n
    for i in range(1, len(arr)):
      cur_n += dif
      if cur_n not in all_n:
        return False

    return True

 

Last Updated on 2023/08/16 by A1go

目錄

目錄
Bitnami