中级农民
- 积分
- 105
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-7-30
- 最后登录
- 1970-1-1
|
我用python 写了一个,大家可以试试有没有bug。
- # [1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3] 则返回12 (取中间6个2相加)
- # [1, 1, 2, 2, 2, 2, 2, 2, 4] 返回16 (因为2和4不连续)
- def maxSum(nums):
- n = len(nums)
- if n < 2:
- return nums[0]
-
- # make the list to val and amount.
- # val is the different number, amount is the amount for each val
- # for example [1, 1, 2, 2, 2, 2, 2, 2, 4]
- # val = [1, 2, 4], amount = [2, 12, 4]
- val = [nums[0]]
- amount = []
- j = 0
- count = 1
- for i in range(1,n):
- if nums[i] == nums[i-1]:
- count += 1
- else:
- amount.append(val[j]*count)
- j += 1
- val.append(nums[i])
- count = 1
- amount.append(val[j]*count)
-
- # print(val, amount)
-
- # below is the algo like house robber
- m = len(val)
- if m < 2:
- return amount[0]
-
- res = [0] * m
- res[0] = amount[0]
- if val[1] > val[0]+1:
- res[1] = sum(amount[:2])
- else:
- res[1] = amount[1]
-
- maxi = res[0]
- for i in range(2, m):
- if val[i] > val[i-1]+1:
- maxi = max(maxi, res[i-1]) # trick part
- res[i] = maxi + amount[i]
- else:
- res[i] = maxi + amount[i]
- maxi = max(maxi, res[i-1])
-
- return max(res), res
复制代码 |
|