K consecutive maxSum

本文探讨了如何寻找数组中连续子数组的最大和,并提出了两种不同的解决方案:一种针对单一最大连续子数组的问题,使用动态规划;另一种针对寻找三个不重叠的连续子数组以形成最大总和的问题,通过递归和动态规划相结合的方法解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 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];
}


### Capacity Constrained K-Means Clustering Algorithm Implementation and Explanation Capacity-constrained k-means clustering is a variant of the traditional k-means algorithm where each cluster has an upper limit on the number of points it can contain. This constraint ensures that clusters do not become too large, which may be desirable in certain applications such as load balancing or resource allocation. The standard k-means objective function minimizes within-cluster variance but does not consider capacity constraints. To incorporate these constraints into the model: - A penalty term must be added to penalize violations of the capacity limits. - The assignment step needs modification so that no more than \( C_i \) points are assigned to any given cluster \( i \). An effective approach involves using Lagrange multipliers to handle inequality constraints during optimization[^1]. Here's how one might implement this method in Python: ```python import numpy as np from sklearn.cluster import MiniBatchKMeans def capacity_constrained_kmeans(X, n_clusters=8, max_iter=300, capacities=None): """ Perform capacity-constrained k-means clustering Parameters: X (array-like): Input data matrix with shape (n_samples, n_features). n_clusters (int): Number of clusters. max_iter (int): Maximum iterations allowed. capacities (list[int]): List containing maximum size per cluster. Returns: labels (ndarray): Array of integer labels indicating cluster membership. centers (ndarray): Centroid coordinates for each cluster. """ if capacities is None: raise ValueError("Capacities list cannot be empty") # Initialize centroids randomly from input samples rng = np.random.RandomState(42) indices = rng.choice(len(X), size=n_clusters, replace=False) centers = X[indices] prev_labels = None for iteration in range(max_iter): distances = ((X[:, :, None] - centers.T)**2).sum(axis=1) # Assign points while respecting capacity restrictions available_slots = capacities.copy() labels = [-1] * len(X) sorted_indices = np.argsort(distances.sum(axis=1)) for idx in sorted_indices: valid_options = [ c for c in range(n_clusters) if available_slots[c] > 0 and distances[idx][c] != float('inf') ] if not valid_options: break chosen_cluster = min(valid_options, key=lambda x: distances[idx][x]) labels[idx] = chosen_cluster available_slots[chosen_cluster] -= 1 # Update center positions based on new assignments updated_centers = [] for clust_id in set(labels): members = [idx for idx, lbl in enumerate(labels) if lbl == clust_id] if members: centroid = X[members].mean(axis=0) updated_centers.append(centroid) centers = np.array(updated_centers) # Check convergence condition if prev_labels is not None and all(prev_labels == labels): break prev_labels = labels[:] return labels, centers ``` This code snippet demonstrates implementing capacity-constrained k-means by ensuring no cluster exceeds its specified capacity when assigning points. It iteratively updates both point-to-cluster assignments and cluster centroids until either reaching `max_iter` iterations or achieving stable results between consecutive passes over the dataset. --related questions-- 1. How would varying initial conditions affect performance? 2. What alternative strategies exist beyond simple distance-based selection? 3. Can parallel processing techniques improve execution speed significantly here? 4. Are there specific use cases better suited for capacity-constrained versus regular k-means?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值