K consecutive maxSum

本文探讨了如何寻找数组中连续子数组的最大和,并提出了两种不同的解决方案:一种针对单一最大连续子数组的问题,使用动态规划;另一种针对寻找三个不重叠的连续子数组以形成最大总和的问题,通过递归和动态规划相结合的方法解决。
// given an array, find n consecutive number which forms the largest sum.
#include "header.h"
using namespace std;

int maxConsecutive(vector<int>& array, int n) {
  if(n <= 0) return 0;
  vector<int> dp(array.size(), 0);
  dp[0] = array[0];
  for(int i = 1; i < array.size(); ++i) {
    dp[i] += dp[i-1] + array[i];
  }
  int maxSum = INT_MIN;
  for(int i = 0; i + n < array.size(); i++) {
      maxSum = max(maxSum, dp[i + n] - dp[i]);
  }
  if(n > array.size()) return dp[array.size() - 1];
  return maxSum;
}

// given an array and a number n, find 3 non-overlap n consecutive numbers which makes the largest sum.
// 1, 3, 7, 7, 2, 1, 1, 4, 8, 8, 6, 1, 1, 9
// 1, 3, (7 7), 2, 1, 1, (4 8), (8, 6), 1, 1, 9
// seems like we can use divide and conquer here.
void maxSum(vector<int>& array, int pos, int currSum, int& maxSumValue, int k, int n) {
  if(k < 0 || pos > array.size()) return;
  if(k == 0) {
    maxSumValue = max(maxSumValue, currSum);
    return;
  }
  for(int i = pos; i + k * n < array.size(); ++i) {
      for(int j = i; j < i + n; ++j) currSum += array[j];
      maxSum(array, i + n, currSum, maxSumValue, k - 1, n);
      for(int j = i; j < i + n; ++j) currSum -= array[j];
  }
}
// maybe think about dynamic programming?


int maxSum(vector<int>& array, int n) {
  if(array.size() < n * 3) return 0;
  int maxSumValue = INT_MIN;
  int currSum = 0;
  int pos = 0;
  maxSum(array, pos, currSum, maxSumValue, 3, n);
  return maxSumValue;
}

int main(void) {
  vector<int> nums{1, 3, 7, 7, 2, 1, 1, 4, 8, 8, 6, 1, 1, 9};
  cout << maxSum(nums, 2) << endl;
}


A bit  update for first question and DP method for second question

// consecutive largest sum.
int kConsecutiveSum(vector<int>& nums, int k) {
  int n = nums.size();
  vector<int> dp(n, 0); dp[0] = nums[0];
  for(int i = 1; i < n; ++i) {
    dp[i] = nums[i] + dp[i-1];
  }
  if(k >= n) return dp[n-1];
  int largestSum = dp[k-1];
  for(int j = k + 1; j < n; ++j) {
      largestSum = max(largestSum, dp[j- 1] - dp[j - k - 1]);
  }
  return largestSum;
}

// K consecutive largest sum.
int kConsecutiveSumII(vector<int>& nums, int k, int n) {
  int size = nums.size();
  vector<int> dp(n, 0); dp[0] = nums[0];
  for(int i = 1; i < nums.size(); ++i) {
    dp[i] = dp[i-1] + nums[i];
  }
  if(k * n >= nums.size()) return dp[nums.size() - 1];
  vector<int> pre(n, 0);
  for(int i = 1; i <= k; ++i) {
    vector<int> curr(n, 0);
    for(int j = i * n; j < nums.size(); ++j) {
      if(j == i * n) curr[j] = dp[j-1];
      else dp[j] = max(dp[j - 1], dp[j - 1] - sum[j - n - 1] + prev[j - n]);
    }
  }
  return dp[nums.size() - 1];
}


### 优化 `calculate_modified_harmonic_series` 函数的方法 为了提高 `calculate_modified_harmonic_series` 函数的效率,可以从算法设计、数据结构选择和并行计算等多个方面进行优化。以下是一些有效的优化策略: #### 1. **使用生成器减少内存占用** 在处理大规模分母范围时,逐项生成分母可以有效降低内存消耗。通过将循环封装为生成器函数,避免一次性加载所有数值到内存中,从而提升性能。 ```python def generate_valid_denominators(n, max_denominator): for k in range(1, max_denominator + 1): if not has_consecutive_digits(k, n): yield k ``` 该方法确保仅在需要时才生成符合条件的分母值,减少不必要的存储开销[^1]。 #### 2. **改进连续数字检测逻辑** 当前的 `has_consecutive_digits` 函数可以通过预处理字符串的方式进一步优化。例如,可以将字符串转换为字符列表,并利用滑动窗口技术快速判断是否存在连续重复的数字。 ```python def has_consecutive_digits(denominator, threshold): s = str(denominator) count = 1 for i in range(1, len(s)): if s[i] == s[i - 1]: count += 1 if count >= threshold: return True else: count = 1 return False ``` 此方法的时间复杂度为 $ O(\log_{10}k) $,对于每个分母来说是线性的,适合大规模计算。 #### 3. **缓存已检查结果以避免重复计算** 由于某些数字模式会在多个分母中重复出现,可以采用字典或集合来缓存已经判断过的分母值,避免重复调用 `has_consecutive_digits` 函数。 ```python checked_cache = {} def is_valid_denominator(k, n, cache=checked_cache): if k in cache: return cache[k] result = not has_consecutive_digits(k, n) cache[k] = result return result ``` 这种缓存机制能显著减少重复判断带来的额外开销,尤其适用于大范围分母的计算场景。 #### 4. **多线程/并行处理加速计算** Python 提供了 `concurrent.futures` 模块,可用于实现并行计算。将整个分母范围划分为多个子区间,并分配给不同的线程或进程处理,最后汇总结果。 ```python from concurrent.futures import ThreadPoolExecutor def parallel_calculate(n, max_denominator, num_threads=4): chunk_size = max_denominator // num_threads futures = [] with ThreadPoolExecutor() as executor: for i in range(num_threads): start = i * chunk_size + 1 end = (i + 1) * chunk_size if i < num_threads - 1 else max_denominator futures.append(executor.submit(calculate_chunk, n, start, end)) total = sum(f.result() for f in futures) return total def calculate_chunk(n, start, end): total = 0.0 for k in range(start, end + 1): if not has_consecutive_digits(k, n): total += 1.0 / k return total ``` 这种方法可以充分利用现代 CPU 的多核特性,大幅缩短整体计算时间[^1]。 #### 5. **提前终止策略(收敛性控制)** 如果目标是近似求和而非精确值,可以在总和变化小于某个阈值时提前终止计算,避免无意义的后续迭代。 ```python epsilon = 1e-8 prev_total = 0.0 for k in range(1, max_denominator + 1): if not has_consecutive_digits(k, n): total += 1.0 / k if abs(total - prev_total) < epsilon: break prev_total = total ``` 此策略特别适用于数学上可能收敛但实际计算中仍需限制最大分母的情况[^1]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值