dp implementation two pointers *1400

Please click on ads to support us..

Python Code:

n=int(input())
a=list(map(int,input().split()))
a1=[a[0]]
a2=[0]
DA=0
if len(set(a))<=2:
    print(n)
else:
    for i in range(n):
        if a[i]!=a1[-1]:
            a1.append(a[i])
            a2.append(i)
    a2.append(n)
    xn1=0
    xn2=1
    i=2
    la1=len(a1)
    while i<la1:
        if a1[i]!=a1[xn1] and a1[i]!=a1[xn2]:
            DA1=a2[i]-a2[xn1]
            if DA<DA1:
                DA=DA1
            xn1=i-1
            xn2=i
        i+=1
    else:
        DA1 = a2[i] - a2[xn1]
        if DA < DA1:
            DA = DA1
    print(DA)

C++ Code:

#include <bits/stdc++.h>
using namespace std;

const int N = 3e6 + 2;
int n, A[N], limit = 1;

int main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    cin >> n;
	for (int i = 0; i < n; i++) cin >> A[i];
	deque<int> mx, mn;
	int i = 0, j;
	for (j = 0; j < n; j++) {
		while (!mx.empty() && A[j] > mx.back()) mx.pop_back();
		while (!mn.empty() && A[j] < mn.back()) mn.pop_back();
		mx.push_back(A[j]);
		mn.push_back(A[j]);
		if (mx.front() - mn.front() > limit) {
			if (mx.front() == A[i]) mx.pop_front();
			if (mn.front() == A[i]) mn.pop_front();
			i++;
		}
	}
	cout << j - i << '\n';
}


Comments

Submit
0 Comments
More Questions

740A - Alyona and copybooks
1491A - K-th Largest Value
922B - Magic Forest
922D - Robot Vacuum Cleaner
408B - Garland
1391A - Suborrays
1700C - Helping the Nature
982A - Row
877A - Alex and broken contest
919D - Substring
362B - Petya and Staircases
1535C - Unstable String
1738F - Connectivity Addicts
1342B - Binary Period
1551C - Interesting Story
794B - Cutting Carrot
534B - Covered Path
1278C - Berry Jam
1203A - Circle of Students
1740B - Jumbo Extra Cheese 2
1740A - Factorise N+M
49B - Sum
23A - You're Given a String
1105C - Ayoub and Lost Array
1624E - Masha-forgetful
998B - Cutting
250A - Paper Work
1740C - Bricks and Bags
1130A - Be Positive
465A - inc ARG