368. Largest Divisible Subset
368. Largest Divisible Subset
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.If there are multiple solutions, return any subset is fine.
Example 1:
nums: [1,2,3] Result: [1,2] (of course, [1,3] will also be ok)
Example 2:
nums: [1,2,4,8] Result: [1,2,4,8]
class Solution { public List<Integer> largestDivisibleSubset(int[] nums) { int n = nums.length; List<Integer> res = new ArrayList<>(); if (n == 0) return res; //maxCount keeps maximum length of a subset that has nums[i] as the largest int[] maxCount = new int[n]; //linkToPrev provides a link to previous number in the DivisibleSubset int[] linkToPrev = new int[n]; Arrays.sort(nums); int maxInd = 0; for (int i = 0; i < n; ++i) { maxCount[i] = 1; //include itself in the subset linkToPrev[i] = -1; //-1 indicates a stop for (int divisor = i - 1; divisor >= 0; --divisor) { //iterate backward to see which divisors can be included if (nums[i] % nums[divisor] == 0) { int includeDivisor = maxCount[divisor] + 1; if (includeDivisor > maxCount[i]) { maxCount[i] = includeDivisor; linkToPrev[i] = divisor; } } } if (maxCount[i] > maxCount[maxInd]) { maxInd = i; } } while (maxInd != -1) { res.add(nums[maxInd]); maxInd = linkToPrev[maxInd]; } return res; } }
Other readings:
https://en.wikipedia.org/wiki/Longest_increasing_subsequence

浙公网安备 33010602011771号