작성일 :

문제 링크

2455번 - 지능형 기차

설명

이 문제는 기차의 각 역에서 내리고 타는 사람 수가 주어졌을 때,
기차에 탑승한 사람 수가 가장 많았던 순간의 인원을 계산하는 문제입니다.


접근법

  • 총 4개의 역에서 사람의 승하차 정보가 주어집니다.
  • 매 단계마다:
    • 먼저 내리는 사람 수를 현재 인원에서 차감합니다.
    • 이어서 타는 사람 수를 현재 인원에 더합니다.
    • 누적 인원이 최대값을 갱신하는지 확인합니다.
  • 각 시점의 인원을 관리하여 최댓값을 추적합니다.

Code

[ C# ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;

namespace Solution {
  class Program {
    static void Main(string[] args) {
      int max = 0, people = 0;
      for (int i = 0; i < 4; i++) {
        var input = Console.ReadLine()!.Split();
        int off = int.Parse(input[0]);
        int on = int.Parse(input[1]);

        people -= off;
        people += on;
        if (people > max) max = people;
      }

      Console.WriteLine(max);
    }
  }
}



[ C++ ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int max = 0, cus = 0;
  for (int i = 0; i < 4; i++) {
    int off, ride; cin >> off >> ride;
    cus -= off; cus += ride;
    if (cus > max) max = cus;
  }

  cout << max << "\n";

  return 0;
}