Skip to content

Commit

Permalink
update +_posts/Tech/algorithms/2018-03-13-动态规划之最大连续子序列和子序列积及递增序列.md
Browse files Browse the repository at this point in the history
  • Loading branch information
Fulong Ma committed Nov 11, 2023
1 parent 5ff5090 commit a69f9b3
Showing 1 changed file with 72 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,27 @@ int MaxSum(int n)
return sum;
}
```
C++:
Python

```python
def max_sum(n, a):
sum_val = 0
b = 0
for i in range(n):
if b > 0:
b += a[i]
else:
b = a[i]
if b > sum_val:
sum_val = b
return sum_val

```



C++: 找最大的对应的左右区间。

```c++
#include <iostream>
#include <vector>
Expand Down Expand Up @@ -143,6 +163,8 @@ class Solution:

```

## 动态规划之最长递增子序列

最长非递减子序列

```python \# 最长非递减子序列
Expand All @@ -157,4 +179,52 @@ def LIS(self, nums: List[int]):
g[j] = x
return len(nums) - len(g)

```
```

## 最大非递减子序列和

- [2926. 平衡子序列的最大和](https://mafulong.eu.org/2023/11/11/2926.-%E5%B9%B3%E8%A1%A1%E5%AD%90%E5%BA%8F%E5%88%97%E7%9A%84%E6%9C%80%E5%A4%A7%E5%92%8C/)



O(nlogn)

线段树维护前面的最大子序列和。每次找小于当前元素的最大子序列和。

```python
MOD = int(1e9 + 7)
INF = float('inf')
import sortedcontainers
import bisect
import heapq

class Solution:
def maxBalancedSubsequenceSum(self, nums: List[int]) -> int:
# len = 12
d = []
n = len(nums)
l = INF
r = float('-inf')
for i in range(n):
if nums[i] > 0:
# l = min(l, nums[i] - i)
# r = max(r, nums[i] - i)
d.append((nums[i] - i, nums[i]))
if not d:
return max(nums)
seg = SegmentTree(SegOpCollect.Collect_Max, SegOpUpdate.Update_SetVal, default_val=0)
diff2index = {}
x = sorted(set([v[0] for v in d]))
for v in x:
diff2index[v] = len(diff2index)
# print(d)
# print(diff2index)
l, r = 0, len(diff2index)
# len = 12
seg.build(left=l, right=r)
for v in d:
t = seg.query_interval(l, diff2index[v[0]])
seg.set_point(diff2index[v[0]], t + v[1])
return seg.query_interval(l, r)
```

0 comments on commit a69f9b3

Please sign in to comment.