国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LintCode/LeetCode] Candy

baishancloud / 3559人閱讀

摘要:保證高的小朋友拿到的糖果更多,我們建立一個分糖果數組。首先,分析邊界條件如果沒有小朋友,或者只有一個小朋友,分別對應沒有糖果,和有一個糖果。排排坐,吃果果。先往右,再往左。右邊高,多一個。總和加上小朋友總數,就是要準備糖果的總數啦。

Problem

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

Each child must have at least one candy.

Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

Example

Given ratings = [1, 2], return 3.

Given ratings = [1, 1, 1], return 3.

Given ratings = [1, 2, 2], return 4. ([1,2,1]).

Note

保證rating高的小朋友拿到的糖果更多,我們建立一個分糖果數組A。小朋友不吃糖果,考試拿A也是可以的。
首先,分析邊界條件:如果沒有小朋友,或者只有一個小朋友,分別對應沒有糖果,和有一個糖果。
然后我們用兩個for循環來更新分糖果數組A
排排坐,吃果果。先往右,再往左。右邊高,多一個。左邊高,吃得多。
這樣,糖果數組可能就變成了類似于[0, 1, 0, 1, 2, 3, 0, 2, 1, 0],小朋友們一定看出來了,這個不是真正的糖果數,而是根據考試級別ratings給高分小朋友的bonus。
好啦,每個小朋友至少要有一個糖果呢。
bonus總和加上小朋友總數n,就是要準備糖果的總數啦。

Solution

</>復制代碼

  1. public class Solution {
  2. public int candy(int[] ratings) {
  3. int n = ratings.length;
  4. if (n < 2) return n;
  5. int[] A = new int[n];
  6. for (int i = 1; i < n; i++) {
  7. if (ratings[i] > ratings[i-1]) A[i] = A[i-1]+1;
  8. }
  9. for (int i = n-2; i >= 0; i--) {
  10. if (ratings[i] > ratings[i+1]) A[i] = Math.max(A[i], A[i+1]+1);
  11. }
  12. int res = n;
  13. for (int a: A) res += a;
  14. return res;
  15. }
  16. }

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/65962.html

相關文章

  • [LintCode/LeetCode] Word Break

    Problem Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words. Example Given s = lintcode, dict = [lint, code]. R...

    dunizb 評論0 收藏0
  • [LintCode/LeetCode] First Unique Character in a S

    Problem Given a string, find the first non-repeating character in it and return its index. If it doesnt exist, return -1. Example Given s = lintcode, return 0. Given s = lovelintcode, return 2. Tags A...

    Xufc 評論0 收藏0
  • [LintCode/LeetCode] Find Median From / Data Stream

    摘要:建立兩個堆,一個堆就是本身,也就是一個最小堆另一個要寫一個,使之成為一個最大堆。我們把遍歷過的數組元素對半分到兩個堆里,更大的數放在最小堆,較小的數放在最大堆。同時,確保最大堆的比最小堆大,才能從最大堆的頂端返回。 Problem Numbers keep coming, return the median of numbers at every time a new number a...

    zxhaaa 評論0 收藏0
  • [LintCode/LeetCode] Implement Trie

    摘要:首先,我們應該了解字典樹的性質和結構,就會很容易實現要求的三個相似的功能插入,查找,前綴查找。既然叫做字典樹,它一定具有順序存放個字母的性質。所以,在字典樹的里面,添加,和三個參數。 Problem Implement a trie with insert, search, and startsWith methods. Notice You may assume that all i...

    付永剛 評論0 收藏0
  • [LintCode/LeetCode] Binary Tree Pruning

    Problem Binary Tree PruningWe are given the head node root of a binary tree, where additionally every nodes value is either a 0 or a 1. Return the same tree where every subtree (of the given tree) not...

    rockswang 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<