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

📅  最后修改于: 2021-09-07 04:43:13             🧑  作者: 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 array
    for(int i = 0; i < n; i++)
    {
         
        // Current element
        int x = a[i];
 
        // Remove index of minimum 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 array
        for (int i = 0; i < n; i++) {
 
            // Current element
            int x = a[i];
 
            // Remove index of minimum 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;
 
        // Function 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 array
    for i in range(n):
 
        # Current element
        x = a[i]
 
        # Remove index of minimum 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 pointer 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
 
    # Function 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 array
  for (int i = 0; i < n; i++)
  {
    // Current element
    int x = a[i];
 
    // Remove index of minimum
    // 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;
 
  // Function call
  Console.WriteLine(maxSubarray(a, k));
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出:
3

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

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