Files
build_infra/0_笔记/数据结构与算法/最大子数组和.md
T
2026-06-16 10:23:51 +08:00

67 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
https://leetcode.cn/problems/maximum-subarray/description/
给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
子数组是数组中的一个连续部分。
示例 1
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
示例 2
输入:nums = [1]
输出:1
示例 3
输入:nums = [5,4,-1,7,8]
输出:23
提示:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。
双指针遍历 n-1 + n-2 + ... + 1 = n*(n-1)/2
如果指针倒过来,结构对称算法仍然不变
穷举状态
定义 n[i] 为第i个元素的值
定义f[i]为offset i所在位置前缀和,两个前缀和相减就是之间的和,仍要双指针遍历
定义f[i]为 offset i 为结尾的 最大子数组和
那么 f[i] = f[i-1] d[i] <= 0
= f[i - 1] + d[i] d[i] > 0
且初始时
f[0] = 0 d[i] <= 0
f[0] = d[0] d[0] > 0
https://leetcode.cn/problems/substring-with-largest-variance/description/?envType=daily-question&envId=2025-03-16
进阶 最大波动子串
字符串的 波动 定义为子字符串中出现次数 最多 的字符次数与出现次数 最少 的字符次数之差。
给你一个字符串 s ,它只包含小写英文字母。请你返回 s 里所有 子字符串的 最大波动 值。
子字符串 是一个字符串的一段连续字符序列。
示例 1
输入:s = "aababbb"
输出:3
解释:
所有可能的波动值和它们对应的子字符串如以下所示:
- 波动值为 0 的子字符串:"a" "aa" "ab" "abab" "aababb" "ba" "b" "bb" 和 "bbb" 。
- 波动值为 1 的子字符串:"aab" "aba" "abb" "aabab" "ababb" "aababbb" 和 "bab" 。
- 波动值为 2 的子字符串:"aaba" "ababbb" "abbb" 和 "babb" 。
- 波动值为 3 的子字符串 "babbb" 。
所以,最大可能波动值为 3 。
示例 2
输入:s = "abcde"
输出:0
解释:
s 中没有字母出现超过 1 次,所以 s 中每个子字符串的波动值都是 0 。
提示:
1 <= s.length <= 104
s 只包含小写英文字母。
穷举状态
第一层双指针遍历出每一个子字符串,第二层求出波动 n(n-1)/2 * o(求波动)
反过来求波动
遍历每一种字母组合 26 * 26
每一种字母组合变为 每一个小部分就变成了最大子数组和
https://leetcode.cn/problems/minimum-number-of-swaps-to-make-the-string-balanced/solutions/922748/shi-zi-fu-chuan-ping-heng-de-zui-xiao-ji-f7ye/?envType=daily-question&envId=2025-03-17