给定大小为n和整数d(这是常见差异)的未排序数组,任务是找到最长AP的长度。 即a [j]在从索引i到j的a [i]的AP中。 例子: Input: n = 6, d = 2 Input: n = 10, d = 3 天真的方法:为每个元素计算它可以形成的最长AP的长度,并在其中打印最大的AP。它涉及O(n 2 )时间复杂度。 一种有效的方法是使用哈希。 创建一个映射,其中键是AP的起始元素,其值是该AP中的元素数。这个想法是每当索引j(> i)的元素可能位于’a的AP中时,将键’a’(位于索引i且其起始元素尚未在地图上的位置)的值更新1。 ‘(作为起始元素)。然后,我们在地图中的所有值中打印最大值。
对于所有j,大于某些i(if a[j] = a[i] + (j-i) * d
arr[] = {1, 2, 5, 7, 9, 85}
Output: 4
The longest AP, taking indices into consideration, is [1, 5, 7, 9]
since 5 is 2 indices ahead of 1 and would fit in the AP if started
from index 0. as 5 = 1 + (2 – 0) * 2. So the output is 4.
arr[] = {1, 4, 2, 5, 20, 11, 56, 100, 20, 23}
Output: 5
The longest AP, taking indices into consideration, is [2, 5, 11, 20, 23]
since 11 is 2 indices ahead of 5 and 20 is 3 indices ahead of 11. So they
would fit in the AP if started from index 2.C++
// C++ code for finding the
// maximum length of AP
#include
Java
// Java code for finding the
// maximum length of AP
import java.io.*;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Map;
import java.lang.*;
class GFG
{
static int maxlenAP(int a[],
int n, int d)
{
// key=starting element of an AP,
// value=length of AP
HashMap
C#
// C# code for finding the
// maximum length of AP
using System;
using System.Collections.Generic;
class GFG
{
static int maxlenAP(int []a,
int n, int d)
{
// key=starting element of an AP,
// value=length of AP
Dictionary
Python 3
# Python code for finding the
# maximum length of AP
def maxlenAP(a, n, d):
# key = starting element of an AP,
# value = length of AP
m = dict()
# since the length of longest AP is at least
# one i.e. the number itself.
maxt = 1
# if element a[i]'s starting element(i.e., a[i]-i*d)
# is not in map then its value is 1 else there already
# exists a starting element of an AP of which a[i]
# can be a part.
for i in range(n):
if (a[i] - i * d) in m:
m[a[i] - i * d] += 1
else:
m[a[i] - i * d] = 1
# In this it variable will be
# storing key value of dictionary.
for it in m:
if m[it] > maxt:
# calculating the length of longest AP.
maxt = m[it]
return maxt
# Driver code
if __name__ == "__main__":
n, d = 10, 3
a = [1, 4, 2, 5, 20, 11, 56, 100, 20, 23]
print(maxlenAP(a, n, d))
# This code is contributed by
# sanjeev2552
5