码迷,mamicode.com
首页 > 其他好文 > 详细

368. Largest Divisible Subset

时间:2016-07-25 06:56:52      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

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
 

368. Largest Divisible Subset

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/5702154.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!