高级农民
- 积分
- 1379
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-6-5
- 最后登录
- 1970-1-1
|
本帖最后由 yf233 于 2022-7-19 14:22 编辑
看了前面大佬的O(n)解法之后按自己理解写了个逻辑更直白的Python解法;- def max_pick(piles):
-
- def _gauss_sum(n, length):
- # gauss sum of a consecutively increasing subarray ending at n
- return (n-length+1+n)*length//2
-
- increase_stack = []
- dp = []
- ans = 0
- for i, count in enumerate(piles):
- # if it follows consecutively increasing subarray pattern, we don't need information about previous items
- consecutive = count-1
- while increase_stack and piles[increase_stack[-1]] >= consecutive:
- increase_stack.pop()
- consecutive -= 1
-
- if increase_stack:
- # if stack not empty, there is a gap in between, so sum is current consecutive subarray + previous sum
- length = i - increase_stack[-1]
- curr = _gauss_sum(count, length) + dp[increase_stack[-1]]
- else:
- # if nothing in stack, then it's a consecutive subarray ends at current count
- length = min(i+1, count)
- curr = _gauss_sum(count, length)
- ans = max(ans, curr)
- dp.append(curr)
- increase_stack.append(i)
- return ans
复制代码 |
|