---
title: leetcode-1103
date: 2020-04-01 11:22:20
tags:
categories: leetcode
mathjax: true
---

### 1103. 分糖果 II

[题目](https://leetcode-cn.com/problems/distribute-candies-to-people/)



<!--more-->



小学奥数题。主要思路就是等差数列求和 $\cfrac{(首项 + 末项)×项数}{2}$ 。可以用公式把每一个位置获得的总糖果数表示出来。我的方法稍微蠢了点，算了每一轮的总糖果数，其实可以直接求总共发了多少次糖果，除以每轮的人数就可以得出发了多少轮。



```python
class Solution:
  def distributeCandies(self, candies: int, num_people: int):
    total = 0
    i = 0
    # import ipdb; ipdb.set_trace()
    while total <= candies:
      t = (num_people*i)*num_people + int((1+num_people)*num_people/2)
      if total + t <= candies:
        total += t
        i += 1
      else:
        break
    remaining = candies - total
    print(total, remaining, i)
    l = []
    for n in range(1, num_people+1):
      if not total:
        current_candy = n
      else:
        current_candy = n+i*num_people

      n_count = int((0+(i-1))*(i)/2)
      print(current_candy, n_count)
      if remaining >= current_candy:
        l.append(n_count*num_people + n*i + current_candy)
        remaining -= current_candy
      else:
        l.append(n_count*num_people + n*i + remaining)
        remaining = 0
    return l
# 28 ms	13.7 MB,
```
