📌  相关文章
📜  以交替递增递减顺序计算具有元素的子数组,反之亦然

📅  最后修改于: 2022-05-13 01:56:06.005000             🧑  作者: Mango

以交替递增递减顺序计算具有元素的子数组,反之亦然

给定一个大小为N的数组arr[] ,任务是找到具有交替递增递减顺序或反之亦然元素的子数组的计数。当且仅当满足 ( a < b > c ) 或 ( a > b < c ) 时,子数组 { a, b, c } 才有效。

例子

方法:可以使用滑动窗口方法和数学概念来解决该任务。该解决方案是使用以下步骤构建的:

  • 找到最长的当前有效子数组。
  • 当当前最长的有效子数组中断时,取最长子数组的长度并将其存储在数组中。
  • 从前一个最长子数组结束的点重新启动窗口并找到下一个最长的窗口并重复直到数组完成。
  • 该数组将具有其中不重叠连续子数组的长度。
  • 对于每个大小为k 的窗口,这是一个有效的子数组,所有可能的任何大小的窗口也是有效的子序列
  • 求一个窗口中所有可能的子序列,如果一个窗口为k,则所有大小的子数组的个数= kx(k-1)/2
  • 对数组中的每个窗口大小执行此操作并将其添加到count
  • 返回计数作为最终答案。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the count
// of valid subarrays
int getSubsequenceCount(vector& nums)
{
 
  bool flag = false;
  vector arr;
  int i = 0, j = 1;
  while (j < nums.size()) {
    if ((nums[j] > nums[j - 1] && flag != true)
        || (nums[j] < nums[j - 1] && flag != false)) {
      if (nums[j] > nums[j - 1])
        flag = true;
      else if (nums[j] < nums[j - 1])
        flag = false;
      j += 1;
    }
 
    else {
      if (j - i != 1) {
        arr.push_back(j - i);
        flag = false;
        i = j - 1;
      }
      else {
        i = j;
        j += 1;
      }
    }
  }
  if (j - i != 1)
    arr.push_back(j - i);
  int count = 0;
 
  // Number of valid subsequences
  for (int itm : arr)
    count += itm * (itm - 1) / 2;
  return count;
}
 
int main()
{
  // Driver code
  vector nums = { 1, 2, 1, 2, 1 };
  cout << getSubsequenceCount(nums) << "\n";
}
 
// This code is contributed by Taranpreet


Java
// Java program for the above approach
import java.util.ArrayList;
 
class GFG
{
 
  // Function to find the count
  // of valid subarrays
  static int getSubsequenceCount(int[] nums) {
 
    boolean flag = false;
    ArrayList arr = new ArrayList();
    int i = 0, j = 1;
    while (j < nums.length) {
      if ((nums[j] > nums[j - 1] && flag != true) ||
          (nums[j] < nums[j - 1] && flag != false)) {
        if (nums[j] > nums[j - 1])
          flag = true;
        else if (nums[j] < nums[j - 1])
          flag = false;
        j += 1;
      }
 
      else {
        if (j - i != 1) {
          arr.add(j - i);
          flag = false;
          i = j - 1;
        } else {
          i = j;
          j += 1;
        }
      }
    }
    if (j - i != 1)
      arr.add(j - i);
    int count = 0;
 
    // Number of valid subsequences
    for (int itm : arr)
      count += itm * (itm - 1) / 2;
    return count;
  }
 
  public static void main(String args[]) {
    // Driver code
    int[] nums = { 1, 2, 1, 2, 1 };
    System.out.println(getSubsequenceCount(nums));
  }
}
 
// This code is contributed gfgking


Python3
# Python program for the above approach
 
# Function to find the count
# of valid subarrays
def getSubsequenceCount(nums):
    flag = None
    length = 1
    arr = []
    i, j = 0, 1
    while j < len(nums):
        if(nums[j] > nums[j-1] and flag != True) \
                or (nums[j] < nums[j-1] \
                    and flag != False):
            if(nums[j] > nums[j-1]):
                flag = True
            elif(nums[j] < nums[j-1]):
                flag = False
            j += 1
        else:
            if(j-i != 1):
                arr.append(j-i)
                flag = None
                i = j-1
            else:
                i = j
                j += 1
    if(j-i != 1):
        arr.append(j-i)
    count = 0
 
    # Number of valid subsequences
    for n in arr:
        count += n*(n-1)//2
    return count
 
# Driver code
if __name__ == "__main__":
    nums = [1, 2, 1, 2, 1]
    print(getSubsequenceCount(nums))


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to find the count
  // of valid subarrays
  static int getSubsequenceCount(int[] nums) {
 
    bool flag = false;
    List arr = new List();
    int i = 0, j = 1;
    while (j < nums.Length) {
      if ((nums[j] > nums[j - 1] && flag != true) ||
          (nums[j] < nums[j - 1] && flag != false)) {
        if (nums[j] > nums[j - 1])
          flag = true;
        else if (nums[j] < nums[j - 1])
          flag = false;
        j += 1;
      }
 
      else {
        if (j - i != 1) {
          arr.Add(j - i);
          flag = false;
          i = j - 1;
        } else {
          i = j;
          j += 1;
        }
      }
    }
    if (j - i != 1)
      arr.Add(j - i);
    int count = 0;
 
    // Number of valid subsequences
    foreach (int itm in arr)
      count += itm * (itm - 1) / 2;
    return count;
  }
 
  static public void Main ()
  {
     
    // Driver code
    int[] nums = { 1, 2, 1, 2, 1 };
    Console.WriteLine(getSubsequenceCount(nums));
  }
}
 
// This code is contributed Shubham Singh


Javascript


输出
10

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