Suppose we have a number N, we have to determine the largest perfect cube that can be generated by removing minimum digits (possibly 0) from the number. We can delete any digit from the given number to reach the target. As we know a number N is called a perfect cube if N = M^3 for some integer M.
So, if the input is like 806, then the output will be 8, as we can delete 0 and 6 from the number, then we will get 8, this is perfect cube of 2.
To solve this, we will follow these steps −
- Define a function preProcess() . This will take n
- temp_cubes := a new list
- for i in range 1 to ceiling of n^(1/3), do
- cube = i^3
- cubeString := cube as string
- insert cubeString at the end of temp_cubes
- return temp_cubes
- Define a function solve() . This will take num,temp_cubes
- reverse temp_cubes
- totalCubes := size of temp_cubes
- for i in range 0 to totalCubes, do
- temp := temp_cubes[i]
- digitsInCube := size of temp
- index := 0
- digitsInNumber := size of num
- for j in range 0 to digitsInNumber, do
- if num[j] is same as temp[index], then
- index := index + 1
- if digitsInCube is same as index, then
- return temp
- if num[j] is same as temp[index], then
- return "Not Possible"
- From the method do the following −
- temp_cubes := preProcess(n)
- num := n as string
- ans := solve(num, temp_cubes)
- return ans
Example
Let us see the following implementation to get better understanding −
import math def preProcess(n): temp_cubes = list() for i in range(1, math.ceil(n**(1. / 3.))): cube = i**3 cubeString = str(cube) temp_cubes.append(cubeString) return temp_cubes def solve(num,temp_cubes): temp_cubes = temp_cubes[::-1] totalCubes = len(temp_cubes) for i in range(totalCubes): temp = temp_cubes[i] digitsInCube = len(temp) index = 0 digitsInNumber = len(num) for j in range(digitsInNumber): if (num[j] == temp[index]): index += 1 if (digitsInCube == index): return temp return "Not Possible" def getLargestCube(n): temp_cubes = preProcess(n) num = str(n) ans = solve(num, temp_cubes) return ans n = 806 print(getLargestCube(n) )
Input
806
Output
8