#C0E2012. 华为OD机试E卷 - 导师请吃火锅

华为OD机试E卷 - 导师请吃火锅

题目链接

华为OD机试E卷 - 导师请吃火锅(Java & Python& JS & C++ & C )

https://blog.csdn.net/banxia_frontend/article/details/141750091 |

贪心解法

import java.util.Arrays;
import java.util.Scanner;
 
public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
 
    int n = sc.nextInt();
    int m = sc.nextInt();
 
    int[] suit = new int[n];
    for (int i = 0; i < n; i++) {
      suit[i] = sc.nextInt() + sc.nextInt();
    }
 
    System.out.println(getResult(n, m, suit));
  }
 
  public static int getResult(int n, int m, int[] suit) {
    Arrays.sort(suit);
 
    int count = 1; // 第1个合适的菜必吃
    int pre = 0;
    for (int i = 1; i < suit.length; i++) {
      if (suit[i] >= suit[pre] + m) {
        // 如果想要捞本次合适的菜,则必须要与上次捞菜的时间差大于等于m,注意这里是suit[pre] + m ,而不是suit[i-1] + m
        count++;
        // 如果本次捞了菜,则更新缓存本次捞菜的时间点
        pre = i;
      }
    }
    return count;
  }
}