题解 | #分糖果问题#
分糖果问题
https://www.nowcoder.com/practice/76039109dd0b47e994c08d8319faa352
using System.Linq;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
class Solution {
public int candy(List<int> arr) {
if (arr.Count == 0) {
return 0;
}
if (arr.Count == 1) {
return 1;
}
var result = parseStudent(arr);
while (true) {
bool rst = SplitCandy(result);
if (!rst) {
break;
}
}
return result.Select(x => x.candy).Sum();
}
public List<Student> parseStudent(List<int> arr) {
var result = new List<Student>();
for (int i = 0; i < arr.Count; i++) {
Student student = new Student();
student.score = arr[i];
student.candy = 1;
student.index = i;
result.Add(student);
if (i > 0) {
student.left = result[i - 1];
}
}
for (int i = 0; i < arr.Count - 1; i++) {
result[i].right = result[i + 1];
}
return result;
}
public bool SplitCandy(List<Student> list) {
bool rst = false;
foreach (var student in list) {
if (student.left != null) {
if (student.score > student.left.score && student.candy <= student.left.candy) {
student.candy = student.left.candy + 1;
rst = true;
}
}
if (student.right != null) {
if (student.score > student.right.score &&
student.candy <= student.right.candy) {
student.candy = student.right.candy + 1;
rst = true;
}
}
}
return rst;
}
}
class Student {
public int index;
public int score;
public int candy;
public Student left;
public Student right;
}
分糖果问题,先每人分一颗,然后检查有没有不符合要求的,再给分多的+1. 直到没有不符合逻辑的地方。

