zoukankan      html  css  js  c++  java
  • 【leetcode】135. Candy

    题目如下:

    解题思路:如下图,只需要找出数组中所有的拐点(前后值相等也认为是拐点)。最低点分配的糖果是1个,最高点分配的糖果是max(到左边最低点的距离,到右边最低点的距离),因为次高点与最低点之间每个点分配的糖果构成公差为1的等差数列,因此很容易就能求出相邻的最高点和最低点组成的线段中所有点分配的糖果的总和,进而求出所有糖果的总和。

    代码如下:

    class Solution(object):
        def candy(self, ratings):
            """
            :type ratings: List[int]
            :rtype: int
            """
            bottomList = [0]
            res = 0
            dp = [1 for x in ratings]
            for i in xrange(1,len(ratings)-1):
                if ratings[i] <= ratings[i-1] and ratings[i] <= ratings[i+1]:
                    bottomList.append(i)
                elif ratings[i] >= ratings[i-1] and ratings[i] >= ratings[i+1]:
                    bottomList.append(i)
            bottomList.append(len(ratings)-1)
            for i in xrange(len(bottomList)-1):
                if ratings[bottomList[i]] > ratings[bottomList[i+1]]:
                    diff = bottomList[i+1] - bottomList[i] + 1
                    count = diff
                    for j in xrange(bottomList[i],bottomList[i+1]+1):
                        dp[j] = max(count,dp[j])
                        count -= 1
                elif ratings[bottomList[i]] < ratings[bottomList[i+1]]:
                    #diff = ratings[bottomList[i+1]] - ratings[bottomList[i]] + 1
                    count = 1
                    for j in xrange(bottomList[i], bottomList[i+1] + 1):
                        dp[j] = max(count, dp[j])
                        count += 1
                else:
                    pass
            #print bottomList
            #print dp
            return sum(dp)
  • 相关阅读:
    流量数据iftop命令
    DNS A记录和CNAME记录
    centos6.5安装mysql
    Python列表插入字典(转)
    列表转字典
    python 二分法O(logn)
    centos 6.5搭建Samba
    反爬虫-----看这一篇就够了
    windows常用命令
    requests中文页面乱码解决方案【转】
  • 原文地址:https://www.cnblogs.com/seyjs/p/9268885.html
Copyright © 2011-2022 走看看