当前位置:网站首页>Huawei machine test question: longest continuous subsequence

Huawei machine test question: longest continuous subsequence

2022-07-05 01:33:00 JOEL-T99

Scala Realization

Title Description :

  • Yes N A sequence of positive integers , Given an integer sum
  • Find the longest continuous subsequence so that their sum equals sum
  • Returns the length of the secondary subsequence , If there is no sequence that meets the requirements return -1

remarks :

  • The input sequence consists only of numbers and English commas , Numbers are separated by English commas
  • Sequence length 1<=N<=200, The input sequence does not consider exceptions
  • The title ensures that the input sequence meets the requirements

Example

Input :

  • 1,2,3,4,2
  • 6

Output :

  • 3

analysis :

  • 1,2,3 and 4,2 Both sequences can meet the requirements , So the longest continuous sequence is 1,2,3 So the result is 3

Input :

  • 1,2,3,4,2
  • 20

Output :

  • -1

explain :

  • There are no subsequences that meet the requirements , return -1

Code :

def main(args: Array[String]): Unit = {
    

    //  Get input 
    val elems = StdIn.readLine().split(",").map(_.toInt).toList
    val sum = StdIn.readLine().toInt

    //  Declare variables 
    var tmp = 0
    var maxLen = -1

    // Calculation  maxLen
    for (i <- elems.indices) {
    

        tmp += elems(i)

        //  Continuously increase the following number , If it is greater than sum Is out of , If it is equal to sum Reset maxLen
        breakable {
    
            for (j <- i + 1 until elems.length) {
    

                tmp += elems(j)

                //  Out of the loop 
                if (tmp > sum) break

                //  Reset maxLen
                if (tmp == sum) {
    

                    maxLen = Math.max(maxLen, j - i + 2)
                    break
                }

                //  If you can't find it, set it to -1
                maxLen = -1
            }
        }

        //  Reset tmp
        tmp = 0
    }

    //  Output results 
    println(maxLen)
}

 


️ END ️
原网站

版权声明
本文为[JOEL-T99]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141027433967.html