Skip to content

Instantly share code, notes, and snippets.

@dailybird
Created July 13, 2018 13:47
Show Gist options
  • Save dailybird/6ccb53fbe3f02845b053a34073aded35 to your computer and use it in GitHub Desktop.
Save dailybird/6ccb53fbe3f02845b053a34073aded35 to your computer and use it in GitHub Desktop.
package com
import scala.collection.mutable
import scala.io.Source
object NonDivisibleSubset {
def main(args: Array[String]): Unit = {
val target = Source.fromFile("").mkString.split(" ").map(_.toInt)
println(target.length)
val result = nonDivisibleSubset(2, target)
println(result)
}
def nonDivisibleSubset(k: Int, S: Array[Int]): Int = {
var maxSubsetLength = 0
// 注意 1
if (1.equals(k)) {
maxSubsetLength = 1
} else {
val hashMap = mutable.HashMap[Int, Int]()
var invalidCount = 0
for (item <- S) {
val remainder = item % k
if (0.equals(remainder) == false) {
val current = hashMap.get(remainder)
current match {
case None => hashMap(remainder) = 1
case Some(_) => hashMap(remainder) += 1
}
}else{
invalidCount += 1
}
}
maxSubsetLength = S.length - invalidCount
if (invalidCount > 0) {
maxSubsetLength += 1
}
var halfOfK = k / 2
if (0.equals(k % 2)) {
val countOfHalfK = hashMap.get(halfOfK)
if (countOfHalfK != None) {
maxSubsetLength = maxSubsetLength - countOfHalfK.get + 1
}
halfOfK = k / 2 - 1
}
for ((key, value) <- hashMap) {
// 注意奇数偶数
if (key <= halfOfK) {
val complement = hashMap.get(k - key)
if (complement != None) {
maxSubsetLength -= Math.min(value, complement.get)
}
}
}
}
maxSubsetLength
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment