【leetcode】Candy

來源:互聯網
上載者:User

標籤:style   blog   color   io   for   re   

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?

 

題解:

  1. 第一個孩子給一顆糖,然後從左至右遍曆rate數組,如果孩子i+1的rate比孩子i的rate高,那麼孩子i+1得到的糖果數目比孩子i得到的糖果數目多1;如果孩子i+1的rate比孩子i的rate低,那麼就給孩子i+1一顆糖;
  2. 從右往左遍曆rate數組,如果當前遍曆的孩子i的rate比他右邊的孩子的rate高,那麼他得到的糖果就比他右邊的孩子得到的糖果多1.
  3. 累加rate中所有的值,得到總的最少糖果數目。

代碼如下:

 1 public class Solution { 2     public int candy(int[] ratings) { 3         if(ratings.length == 0) 4             return 0; 5          6         int[] count = new int[ratings.length]; 7         Arrays.fill(count, 1); 8          9         for(int i = 1;i <= ratings.length-1;i++){10             if(ratings[i]> ratings[i-1] )11                 count[i] = count[i-1] + 1; 12         }13         14         int sum = 0;15         for(int i = ratings.length-1;i >= 1;i--){16             sum += count[i];17             if(ratings[i-1] > ratings[i] && count[i-1] <= count[i])18                 count[i-1] = count[i]+ 1; 19         }20         21         return count[0] + sum;22     }23 }

在17行的迴圈,需要判斷i-1個孩子當前獲得的糖果數目是否真的比第i個孩子的少,如果真的少,才需要+1.例如:

ratings = {4,2,3,4,1}的時候,第一遍遍曆得到的count數組是{1,1,2,3,1},此時從後往前遍曆的時候ratings[3] > ratings[4],但是count[3]已經大於count[4]了,所以不需要更新count[3] = count[4]+1。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.