Largest Divisible Subset
LeetCode 368 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Sorted + 'divides' is transitive ⇒ it's LIS with % instead of <.
ನಾನು Largest Divisible Subset (LeetCode 368) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — LIS ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
After sorting, divisibility chains like LIS: if b divides c and a divides b, then a divides c. So dp[i] = longest chain ending at nums[i] where each earlier element divides the next. Store a back-pointer so the chain itself can be rebuilt.
Approach
- 1
Sort the numbers.
- 2
dp[i] = 1 initially; prev[i] = -1.
- 3
For each j < i with nums[i] % nums[j] == 0, extend if dp[j] + 1 beats dp[i] and remember j.
- 4
Track the index of the longest chain.
- 5
Follow prev pointers back from that index and reverse.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
LIS with back-pointersPythonO(n²) time · O(n) space
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
#longest divisible subsequence
#print lis
nums.sort()
n = len(nums)
prev=[-1]*n
dp=[1]*n
max_index=0
for i in range(n):
for j in range(i):
if nums[i]%nums[j]==0 and dp[j]+1>dp[i]:
dp[i]=dp[j]+1
prev[i]=j
if dp[i]>dp[max_index]:
max_index=i
res=[]
while max_index!=-1:
res.append(nums[max_index])
max_index=prev[max_index]
return res[::-1]Largest Divisible Subset — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Largest Divisible Subset ಹಿಂದಿನ intuition ಏನು?
After sorting, divisibility chains like LIS: if b divides c and a divides b, then a divides c. So dp[i] = longest chain ending at nums[i] where each earlier element divides the next. Store a back-pointer so the chain itself can be rebuilt.
Largest Divisible Subset (LeetCode 368) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Sort the numbers. 2. dp[i] = 1 initially; prev[i] = -1. 3. For each j < i with nums[i] % nums[j] == 0, extend if dp[j] + 1 beats dp[i] and remember j. 4. Track the index of the longest chain. 5. Follow prev pointers back from that index and reverse.
Largest Divisible Subset ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n²). Space: O(n). (Accepted approach: LIS with back-pointers.)
Largest Divisible Subset ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Sorting first is what makes checking only the last element enough. Several answers can be valid — any longest chain is accepted.