📌  相关文章
📜  通过最多执行K个增量操作来最大化相等元素的子数组的长度

📅  最后修改于: 2021-05-17 21:19:40             🧑  作者: Mango

给定由N个整数和整数K组成的数组A [] ,任务是在对数组元素执行最多K个增量1之后,最大化具有相等元素的子数组的长度。

注意:同一数组元素可以增加一次以上。

例子:

天真的方法:解决该问题的最简单方法是生成所有可能的子数组,并针对每个子数组检查所有元素是否最多可以K个增量相等。打印获得的此类子数组的最大长度。
时间复杂度: O(N 3 )
辅助空间: O(1)

方法:可以使用“滑动窗口”技术优化上述方法。请按照以下步骤解决问题:

  • 跟踪窗口的最大元素。
  • 特定窗口所需的全部操作可通过以下公式获得:
  • 现在,检查以上计算的值是否超过K。如果是这样,则将窗口的起始指针向右滑动,否则增加到目前为止计算的窗口的长度。
  • 重复上述步骤,以获得满足所需条件的最长窗口。

下面是上述方法的实现:

C++14
// C++14 program for above approach
#include 
using namespace std;
#define newl "\n"
 
// Function to find the maximum length
// of subarray of equal elements after
// performing at most K increments
int maxSubarray(int a[], int k, int n)
{
 
    // Stores the size
    // of required subarray
    int answer = 0;
 
    // Starting point of a window
    int start = 0;
 
    // Stores the sum of window
    long int s = 0;
 
    deque dq;
 
    // Iterate over arrray
    for(int i = 0; i < n; i++)
    {
         
        // Current element
        int x = a[i];
 
        // Remove index of minimun elements
        // from deque which are less than
        // the current element
        while (!dq.empty() &&
               a[dq.front()] <= x)
            dq.pop_front();
 
        // Insert current index in deque
        dq.push_back(i);
 
        // Update current window sum
        s += x;
 
        // Calculate required operation to
        // make current window elements equal
        long int cost = (long int)a[dq.front()] *
                        (answer + 1) - s;
 
        // If cost is less than k
        if (cost <= (long int)k)
            answer++;
 
        // Shift window start pointer towards
        // right and update current window sum
        else
        {
            if (dq.front() == start)
                dq.pop_front();
                 
            s -= a[start++];
        }
    }
     
    // Return answer
    return answer;
}
 
// Driver Code
int main()
{
    int a[] = { 2, 2, 4 };
    int k = 10;
     
    // Length of array
    int n = sizeof(a) / sizeof(a[0]);
     
    cout << (maxSubarray(a, k, n));
     
    return 0;
}
 
// This code is contributed by jojo9911


Java
// Java Program for above approach
import java.util.*;
 
class GFG {
 
    // Function to find the maximum length
    // of subarray of equal elements after
    // performing at most K increments
    static int maxSubarray(int[] a, int k)
    {
        // Length of array
        int n = a.length;
 
        // Stores the size
        // of required subarray
        int answer = 0;
 
        // Starting point of a window
        int start = 0;
 
        // Stores the sum of window
        long s = 0;
 
        Deque dq = new LinkedList<>();
 
        // Iterate over arrray
        for (int i = 0; i < n; i++) {
 
            // Current element
            int x = a[i];
 
            // Remove index of minimun elements
            // from deque which are less than
            // the current element
            while (!dq.isEmpty() && a[dq.peek()] <= x)
                dq.poll();
 
            // Insert current index in deque
            dq.add(i);
 
            // Update current window sum
            s += x;
 
            // Calculate required operation to
            // make current window elements equal
            long cost
                = (long)a[dq.peekFirst()] * (answer + 1)
                  - s;
 
            // If cost is less than k
            if (cost <= (long)k)
                answer++;
 
            // Shift window start pointer towards
            // right and update current window sum
            else {
                if (dq.peekFirst() == start)
                    dq.pollFirst();
                s -= a[start++];
            }
        }
 
        // Return answer
        return answer;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int[] a = { 2, 2, 4 };
        int k = 10;
 
        // Funtion call
        System.out.println(maxSubarray(a, k));
    }
}


Python3
# Python3 program for above approach
from collections import deque
 
# Function to find the maximum length
# of subarray of equal elements after
# performing at most K increments
def maxSubarray(a, k):
     
    # Length of array
    n = len(a)
 
    # Stores the size
    # of required subarray
    answer = 0
 
    # Starting po of a window
    start = 0
 
    # Stores the sum of window
    s = 0
 
    dq = deque()
 
    # Iterate over arrray
    for i in range(n):
 
        # Current element
        x = a[i]
 
        # Remove index of minimun elements
        # from deque which are less than
        # the current element
        while (len(dq) > 0 and a[dq[-1]] <= x):
            dq.popleft()
 
        # Insert current index in deque
        dq.append(i)
 
        # Update current window sum
        s += x
 
        # Calculate required operation to
        # make current window elements equal
        cost = a[dq[0]] * (answer + 1) - s
 
        # If cost is less than k
        if (cost <= k):
            answer += 1
 
        # Shift window start poer towards
        # right and update current window sum
        else:
            if (dq[0] == start):
                dq.popleft()
                 
            s -= a[start]
            start += 1
 
    # Return answer
    return answer
 
# Driver Code
if __name__ == '__main__':
     
    a = [ 2, 2, 4 ]
    k = 10
 
    # Funtion call
    print(maxSubarray(a, k))
 
# This code is contributed by mohit kumar 29


C#
// C# Program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the maximum length
// of subarray of equal elements after
// performing at most K increments
static int maxSubarray(int[] a, int k)
{
  // Length of array
  int n = a.Length;
 
  // Stores the size
  // of required subarray
  int answer = 0;
 
  // Starting point of a window
  int start = 0;
 
  // Stores the sum of window
  long s = 0;
 
  Queue dq = new Queue();
 
  // Iterate over arrray
  for (int i = 0; i < n; i++)
  {
    // Current element
    int x = a[i];
 
    // Remove index of minimun
    // elements from deque
    // which are less than
    // the current element
    while (dq.Count!=0 &&
           a[dq.Peek()] <= x)
      dq.Dequeue();
 
    // Insert current
    // index in deque
    dq.Enqueue(i);
 
    // Update current window sum
    s += x;
 
    // Calculate required operation to
    // make current window elements equal
    long cost = (long)a[dq.Peek()] *
                (answer + 1) - s;
 
    // If cost is less than k
    if (cost <= (long)k)
      answer++;
 
    // Shift window start pointer towards
    // right and update current window sum
    else
    {
      if (dq.Peek() == start)
        dq.Dequeue();
      s -= a[start++];
    }
  }
 
  // Return answer
  return answer;
}
 
// Driver Code
public static void Main(String[] args)
{
  int[] a = {2, 2, 4};
  int k = 10;
 
  // Funtion call
  Console.WriteLine(maxSubarray(a, k));
}
}
 
// This code is contributed by gauravrajput1


输出:
3



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