题解 | #分糖果问题#

分糖果问题

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. 直到没有不符合逻辑的地方。

全部评论

相关推荐

想申请延毕了,找工作找到崩溃,越找就越想摆烂,还有25届的和我一样感受吗?
码农索隆:没事哒,好兄弟,慢慢来,调整心态,车到山前必有路,感到迷茫的时候,多抬头看看
点赞 评论 收藏
分享
04-14 20:10
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务