Syntax error Largest product of contiguous digits in Python

Largest product of contiguous digits in Python



Suppose we have two numbers num and k, we have to find the largest product of k contiguous digits in num. We have to keep in mind that num is guaranteed to have >= k digits.

So, if the input is like num = 52689762 and k = 4, then the output will be 3024, largest product of 4 consecutive digits is (8*9*7*6) = 3024.

To solve this, we will follow these steps −

  • largest := 0
  • cand := 1
  • while (quotient of num/10)^(k-1) > 0, do
    • digits := (last digit of nums)^k
    • cand := 1
    • while digits > 0, do
      • cand := cand * (digits mod 10)
      • if cand is same as 0, then
        • come out from the loop
      • digits := quotient of digits / 10
    • largest := maximum of largest and cand
    • num := quotient of nums / 10
  • return largest

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, num, k):
      largest = 0
      while num // 10 ** (k - 1) > 0:
         digits = num % 10 ** k
         cand = 1
         while digits > 0:
            cand *= digits % 10
            if cand == 0:
               break
               digits //= 10
               largest = max(largest, cand)
               num //= 10
      return largest
ob = Solution()
num = 52689762
k = 4
print(ob.solve(num,k))

Input

52689762, 4

Output

3024
Updated on: 2020-09-23T07:34:26+05:30

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements