📌  相关文章
📜  最多由 K 个远距离元素组成的最大和子序列,包括第一个和最后一个数组元素

📅  最后修改于: 2021-09-06 05:17:28             🧑  作者: Mango

给定一个由N 个整数和一个整数K组成的数组 arr[] ,任务是打印满足以下条件的子序列中可能的最大和:

  1. 元素arr[N – 1]arr[0]包含在子序列中。
  2. 子序列中的相邻元素的距离最多为K 个索引。

例子:

朴素的方法:最简单的方法是从arr[] 中找到所有可能的子序列,相邻元素的索引之间最多有K 个差异,从索引 0开始,到索引(N – 1) 结束。计算所有这些子序列的总和。最后,打印获得的所有和的最大值。
时间复杂度: O(N*2 N )
辅助空间: O(N)

高效方法:上述方法可以通过使用贪心算法和双端队列进行优化。请按照以下步骤解决问题:

  • 初始化一个数组,比如dp[] ,以存储直到当前索引为止获得的最大值。
  • 初始化一对双端队列,比如Q ,以存储对{dp[i], i}
  • 将 arr[0]的值分配给dp[0]并将 {dp[0], 0}对推入双端队列。
  • 使用变量i遍历给定数组arr[]并执行以下步骤:
    • 通过 arr[i]和双端队列中最大值的总和增加dp[i] ,即 dp[i] = arr[i] + Q[0][0]
    • 如果 Q[-1][0]小于dp[i] ,则从末尾遍历双端队列Q并弹出最后一个元素。
    • 在双端队列中附加{dp[i], i} 对。
    • 检查双端队列 q的第一个元素的索引是否等于(i – K) ,然后从双端队列Q 中弹出第一个元素。
  • 完成上述步骤后,将存储在dp[]的最后一个索引处的值,即dp[N – 1]作为结果打印出来。

下面是上述方法的实现:

C++
// CPP program for the above approach
#include
using namespace std;
 
// Function to find maximum sum
// of a subsequence satisfying
// the given conditions
int maxResult(int arr[], int k, int n){
 
  // Stores the maximum sum
  int dp[n] = {0};
 
  // Starting index of
  // the subsequence
  dp[0] = arr[0];
 
  // Stores the pair of maximum value
  // and the index of that value
  deque> q;
  q.push_back({arr[0], 0});
 
  // Traverse the array
  for (int i = 1; i < n; i++)
  {
 
    // Increment the first value
    // of deque by arr[i] and
    // store it in dp[i]
    dp[i] = arr[i] + q.front().first;
 
    // Delete all the values which
    // are less than dp[i] in deque
    while (q.size() > 0 and q.back().first < dp[i])
      q.pop_back();
 
    // Append the current pair of
    // value and index in deque
    q.push_back({dp[i], i});
 
    // If first value of the
    // queue is at a distance > K
    if (i - k == q.front().second)
      q.pop_front();
  }
 
  // Return the value at the last index
  return dp[n - 1];
}
 
// Driver Code
int main()
{
  int arr[] = {10, -5, -2, 4, 0, 3};
  int K = 3;
  int n = sizeof(arr)/sizeof(arr[0]);
  cout<


Python3
# Python program for the above approach
from collections import deque
 
# Function to find maximum sum
# of a subsequence satisfying
# the given conditions
def maxResult(arr, k):
 
    # Stores the maximum sum
    dp = [0]*len(arr)
 
    # Starting index of
    # the subsequence
    dp[0] = arr[0]
 
    # Stores the pair of maximum value
    # and the index of that value
    q = deque([(arr[0], 0)])
 
    # Traverse the array
    for i in range(1, len(arr)):
       
        # Increment the first value
        # of deque by arr[i] and
        # store it in dp[i]
        dp[i] = arr[i] + q[0][0]
 
        # Delete all the values which
        # are less than dp[i] in deque
        while q and q[-1][0] < dp[i]:
            q.pop()
 
        # Append the current pair of
        # value and index in deque
        q.append((dp[i], i))
         
        # If first value of the
        # queue is at a distance > K
        if i - k == q[0][1]:
            q.popleft()
 
    # Return the value at the last index
    return dp[-1]
 
# Driver Code
 
arr = [10, -5, -2, 4, 0, 3]
K = 3
print(maxResult(arr, K))


输出:
17

时间复杂度: O(N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live