Pintia problem solution - 7-4 Find the student with the highest score

7-4 Find the student with the highest score

Original title:

Given the basic information of N students, including student number (a string composed of 5 numbers), name (a non-empty string with a length less than 10 and not containing whitespace characters) and grades of 3 courses ([0,100] interval an integer within), it is required to output the name, student number and total score of the student with the highest total score.

Input format:

The input gives a positive integer N (≤10) in a row. Then there are N lines, each line gives the information of a student, in the format of "student number, name, grade 1, grade 2, grade 3", separated by spaces.

** Output format: **

Output the name, student ID number and total score of the student with the highest score in one line, separated by a space. The question ensures that such a student is unique.

.

Problem-solving ideas:

Problem-solving ideas:

  1. First, we need to read the input number of students N.
  2. Then, we need to use a loop to read each student's information and find the student with the highest total score.
  3. In the loop, we will read each student's student number, name, and grades for the three courses in sequence.
  4. We calculate each student's total score and compare it to the current highest total score. If the current student's total score is higher, we update the highest total score and the associated student's name and student number.
  5. After the loop ends, we output the name, student ID and total score of the student with the highest total score.

.

JavaScript (node) code:

const readline = require("readline");

// 创建接口
const rl = readline.createInterface({
    
    
  input: process.stdin,
  output: process.stdout
});

// 提示输入学生人数
rl.question('', (n) => {
    
    
  recursionInput(parseInt(n));
});

// 递归读取学生信息
function recursionInput(n) {
    
    
  let maxName = '';
  let maxId = '';
  let maxScore = 0;
    
  // 获取输入信息
  const getInput = (count) => {
    
    
    // 当读取到 n 个学生时,输出最高总分学生信息并关闭接口
    if (count === n) {
    
    
      console.log(`${
      
      maxName} ${
      
      maxId} ${
      
      maxScore}`);
      rl.close();
      return;
    }
    
    // 依次读取学生信息
    rl.question('', (input) => {
    
    
        const [id, name, s1, s2, s3] = input.split(" ");
        const totalScore = parseInt(s1) + parseInt(s2) + parseInt(s3);
        
        // 更新最高总分学生信息
        if (totalScore > maxScore) {
    
    
          maxScore = totalScore;
          maxName = name;
          maxId = id;
        }

      // 继续读取下一个学生信息
      getInput(count + 1);
    });
  };

  // 开始读取第一个学生信息
  getInput(0);
}

Complexity analysis:

Time complexity: O(n)
Space complexity: O(1)

Guess you like

Origin blog.csdn.net/Mredust/article/details/132914432