Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Split an integer n ≥ 2 into at least two positive parts to maximise the product of the parts.
Problem: Split an integer n ≥ 2 into at least two positive parts to maximise the product of the parts.
def int_break(n):
dp = [0, 1] + [0] * (n - 1)
for i in range(2, n + 1):
dp[i] = max(max(j, dp[j]) * (i - j) for j in range(1, i))
return dp[n]
print(int_break(2), int_break(8), int_break(11))What is printed?- A. 1 16 54
- B. 1 18 81
- C. 2 18 54
- D. 1 18 54
Correct answer: D. 1 18 54
For each first cut j, the left part is either kept whole (j) or split further (dp[j]). 2 must split into 1 + 1 → 1. 8 = 3 + 3 + 2 → 18; 11 = 3 + 3 + 3 + 2 → 54. The math shortcut 'use as many 3s as possible, never a 1' agrees. O(n²) DP.
More Coding Interview Problems questions
- Problem: A cable of length n is cut into pieces; prices[k − 1] is the price of a piece of length k. Maximise revenue (unbounded knapsack)…
- Problem: Count subsets of distinct-position items whose values sum exactly to the target (0/1 counting knapsack with a 1-D array iterated…
- Problem: Compare the longest common SUBSTRING (contiguous) with the longest common SUBSEQUENCE of two log fragments. python def lcsub(a…
- Problem: Find the length of the shortest string that contains both a and b as subsequences: |a| + |b| − LCS(a, b). python def lcs(a, b)…
- Problem: Count the ways to roll n dice with k faces each so that the faces sum to target (mod 10⁹ + 7). python def dice(n, k, target…
- Problem: Picking a value v earns v points but deletes every v − 1 and v + 1 from the array; repeat until empty. Maximise points (reduces…