Skip to content

Instantly share code, notes, and snippets.

@themichaelyang
Created September 25, 2023 01:54
Show Gist options
  • Save themichaelyang/ccf590ce5f84bf544f4ca99fb20fd32f to your computer and use it in GitHub Desktop.
Save themichaelyang/ccf590ce5f84bf544f4ca99fb20fd32f to your computer and use it in GitHub Desktop.
def max_score(card_points, k)
left_sums = cumulative_sum(card_points[0...k]).prepend(0)
right_sums = cumulative_sum(card_points[-k..-1].reverse_each).reverse.append(0)
left_sums.zip(right_sums).map(&:sum).max
end
def cumulative_sum(iter)
sum = 0
iter.map {|x| sum += x}
end
@themichaelyang
Copy link
Author

# Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
def product_except_self(nums)
  n = nums.length
  result = [1] * n

  # Populate result with left product
  result.each_index do |i|

    # Keep the first value 1, so that we ignore the value at i
    next if i == 0

    result[i] = result[i - 1] * nums[i - 1]
  end
  # Now, result[i] is the exclusive left product of i

  # Populate the result and get the right product, while using the existing left product
  right_product = 1
  result.each_index do |i|
    j = n - i - 1

    left_product = result[j]
    result[j] = left_product * right_product

    # We exclude the current index in the right product, so we multiply only after populating result
    right_product *= nums[j]
  end

  result
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment