The only difference between easy and hard versions is a number of elements in the array.

You are given an array $a$ consisting of $n$ integers. The value of the $i$-th element of the array is $a_i$.

You are also given a set of $m$ segments. The $j$-th segment is $[l_j; r_j]$, where $1 \le l_j \le r_j \le n$.

You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $a = [0, 0, 0, 0, 0]$ and the given segments are $[1; 3]$ and $[2; 4]$ then you can choose both of them and the array will become $b = [-1, -2, -2, -1, 0]$.

You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $a$ and obtain the array $b$ then the value $\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$ will be maximum possible.

Note that you can choose the empty set.

If there are multiple answers, you can print any.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.


-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n \le 10^5, 0 \le m \le 300$) — the length of the array $a$ and the number of segments, respectively.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^6 \le a_i \le 10^6$), where $a_i$ is the value of the $i$-th element of the array $a$.

The next $m$ lines are contain two integers each. The $j$-th of them contains two integers $l_j$ and $r_j$ ($1 \le l_j \le r_j \le n$), where $l_j$ and $r_j$ are the ends of the $j$-th segment.


-----Output-----

In the first line of the output print one integer $d$ — the maximum possible value $\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$ if $b$ is the array obtained by applying some subset of the given segments to the array $a$.

In the second line of the output print one integer $q$ ($0 \le q \le m$) — the number of segments you apply.

In the third line print $q$ distinct integers $c_1, c_2, \dots, c_q$ in any order ($1 \le c_k \le m$) — indices of segments you apply to the array $a$ in such a way that the value $\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$ of the obtained array $b$ is maximum possible.

If there are multiple answers, you can print any.


-----Examples-----
Input
5 4
2 -2 3 1 2
1 3
4 5
2 5
1 3

Output
6
2
4 1 

Input
5 4
2 -2 3 1 4
3 5
3 4
2 4
2 5

Output
7
2
3 2 

Input
1 0
1000000

Output
0
0




-----Note-----

In the first example the obtained array $b$ will be $[0, -4, 1, 1, 2]$ so the answer is $6$.

In the second example the obtained array $b$ will be $[2, -3, 1, -1, 4]$ so the answer is $7$.

In the third example you cannot do anything so the answer is $0$.

Difficulty: HARD
Tags: Data structures

Implementation
Skill types: Data structures

Starter code:

Solutions:
import sys
big = 10 ** 9

class super_seg:

	def __init__(self, data):
		n = len(data)
		m = 1
		while m < n:
			m *= 2
		self.n = n
		self.m = m
		self.data = [big] * (2 * m)
		for i in range(n):
			self.data[i + m] = data[i]
		for i in reversed(list(range(m))):
			self.data[i] = min(self.data[2 * i], self.data[2 * i + 1])
		self.query = [0] * (2 * m)

	def push(self, seg_ind):
		q = self.query[seg_ind]
		self.query[2 * seg_ind] += q
		self.query[2 * seg_ind + 1] += q
		self.data[2 * seg_ind] += q
		self.data[2 * seg_ind + 1] += q
		self.data[seg_ind] = min(self.data[2 * seg_ind], self.data[2 * seg_ind + 1])
		self.query[seg_ind] = 0

	def update(self, seg_ind):
		seg_ind //= 2
		inds = []
		while seg_ind > 0:
			inds.append(seg_ind)
			seg_ind //= 2
		for ind in reversed(inds):
			self.push(ind)

	def build(self, seg_ind):
		seg_ind //= 2
		while seg_ind > 0:
			self.data[seg_ind] = min(self.data[2 * seg_ind], self.data[2 * seg_ind + 1]) + self.query[seg_ind]
			seg_ind //= 2

	def add(self, l, r, value):
		l += self.m
		r += self.m
		l0 = l
		r0 = r
		while l < r:
			if l % 2 == 1:
				self.query[l] += value
				self.data[l] += value
				l += 1
			if r % 2 == 1:
				r -= 1
				self.query[r] += value
				self.data[r] += value
			l //= 2
			r //= 2
		self.build(l0)
		self.build(r0 - 1)

	def min(self, l, r):
		l += self.m
		r += self.m
		self.update(l)
		self.update(r - 1)
		segs = []
		while l < r:
			if l % 2 == 1:
				segs.append(l)
				l += 1
			if r % 2 == 1:
				r -= 1
				segs.append(r)
			l //= 2
			r //= 2
		return min((self.data[ind] for ind in segs))

	def find_min(self, l, r):
		l += self.m
		r += self.m
		self.update(l)
		self.update(r - 1)
		segs = []
		while l < r:
			if l % 2 == 1:
				segs.append(l)
				l += 1
			if r % 2 == 1:
				r -= 1
				segs.append(r)
			l //= 2
			r //= 2
		ind = min(segs, key=lambda i: self.data[i])
		mini = self.data[ind]
		while ind < self.m:
			self.push(ind)
			if self.data[2 * ind] == mini:
				ind *= 2
			else:
				ind = 2 * ind + 1
		return (ind - self.m, mini)
(n, m) = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
inter = []
update = [[] for _ in range(n + 1)]
for _ in range(m):
	(l, r) = [int(x) for x in input().split()]
	l -= 1
	inter.append((l, r))
	update[l].append((l, r))
	update[r].append((l, r))
Aneg = super_seg([-a for a in A])
besta = -1
besta_ind = -1
active_intervals = 0
for i in range(n):
	for (l, r) in update[i]:
		Aneg.add(l, r, 1 if l == i else -1)
		active_intervals += 1 if l == i else -1
	Amax = -Aneg.data[1]
	Ai = A[i] - active_intervals
	if Amax - Ai > besta:
		besta = Amax - Ai
		besta_ind = i
ints = [i for i in range(m) if inter[i][0] <= besta_ind < inter[i][1]]
print(besta)
print(len(ints))
print(*[x + 1 for x in ints])


import sys

class super_seg:

	def __init__(self, data):
		n = len(data)
		m = 1
		while m < n:
			m *= 2
		self.n = n
		self.m = m
		self.data = [0] * (2 * m)
		for i in range(n):
			self.data[i + m] = data[i]
		for i in reversed(range(m)):
			self.data[i] = min(self.data[2 * i], self.data[2 * i + 1])
		self.query = [0] * (2 * m)

	def push(self, seg_ind):
		q = self.query[seg_ind]
		self.query[2 * seg_ind] += q
		self.query[2 * seg_ind + 1] += q
		self.data[2 * seg_ind] += q
		self.data[2 * seg_ind + 1] += q
		self.data[seg_ind] = min(self.data[2 * seg_ind], self.data[2 * seg_ind + 1])
		self.query[seg_ind] = 0

	def update(self, seg_ind):
		seg_ind //= 2
		inds = []
		while seg_ind > 0:
			inds.append(seg_ind)
			seg_ind //= 2
		for ind in reversed(inds):
			self.push(ind)

	def build(self, seg_ind):
		seg_ind //= 2
		while seg_ind > 0:
			self.data[seg_ind] = min(self.data[2 * seg_ind], self.data[2 * seg_ind + 1]) + self.query[seg_ind]
			seg_ind //= 2

	def add(self, l, r, value):
		l += self.m
		r += self.m
		l0 = l
		r0 = r
		while l < r:
			if l % 2 == 1:
				self.query[l] += value
				self.data[l] += value
				l += 1
			if r % 2 == 1:
				r -= 1
				self.query[r] += value
				self.data[r] += value
			l //= 2
			r //= 2
		self.build(l0)
		self.build(r0 - 1)

	def min(self, l, r):
		l += self.m
		r += self.m
		self.update(l)
		self.update(r - 1)
		segs = []
		while l < r:
			if l % 2 == 1:
				segs.append(l)
				l += 1
			if r % 2 == 1:
				r -= 1
				segs.append(r)
			l //= 2
			r //= 2
		return min((self.data[ind] for ind in segs))

	def find_min(self, l, r):
		l += self.m
		r += self.m
		self.update(l)
		self.update(r - 1)
		segs = []
		while l < r:
			if l % 2 == 1:
				segs.append(l)
				l += 1
			if r % 2 == 1:
				r -= 1
				segs.append(r)
			l //= 2
			r //= 2
		ind = min(segs, key=lambda i: self.data[i])
		mini = self.data[ind]
		while ind < self.m:
			self.push(ind)
			if self.data[2 * ind] == mini:
				ind *= 2
			else:
				ind = 2 * ind + 1
		return (ind - self.m, mini)
(n, m) = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
inter = []
inter2 = []
for _ in range(m):
	(l, r) = [int(x) for x in input().split()]
	l -= 1
	inter.append((l, r))
	inter2.append((r, l))
inter_copy = inter[:]
inter.sort()
inter2.sort()
Aneg = super_seg([-a for a in A])
besta = -1
besta_ind = -1
j1 = 0
j2 = 0
for i in range(n):
	while j1 < m and inter[j1][0] <= i:
		(l, r) = inter[j1]
		Aneg.add(l, r, 1)
		j1 += 1
	while j2 < m and inter2[j2][0] <= i:
		(r, l) = inter2[j2]
		Aneg.add(l, r, -1)
		j2 += 1
	Amax = -Aneg.min(0, n)
	Ai = -Aneg.min(i, i + 1)
	if Amax - Ai > besta:
		besta = Amax - Ai
		besta_ind = i
ints = [j for j in range(m) if inter_copy[j][0] <= besta_ind < inter_copy[j][1]]
print(besta)
print(len(ints))
print(*[x + 1 for x in ints])


def main():
	(n, m) = list(map(int, input().split()))
	aa = list(map(int, input().split()))
	res = max(aa) - min(aa)
	(ll, rr) = ([n + 1], [n + 1])
	segments = res_segments = [False] * (m + 1)
	bounds = {0, n, n + 1}
	for _ in range(m):
		(l, r) = list(map(int, input().split()))
		l -= 1
		ll.append(l)
		rr.append(r)
		bounds.add(l)
		bounds.add(r)
	xlat = sorted(bounds)
	(mi, ma) = ([], [])
	for (l, r) in zip(xlat, xlat[1:-1]):
		t = aa[l:r]
		mi.append(min(t))
		ma.append(max(t))
	bounds = {x: i for (i, x) in enumerate(xlat)}
	for xx in (ll, rr):
		for (i, x) in enumerate(xx):
			xx[i] = bounds[x]
	(il, ir) = (sorted(list(range(m + 1)), key=xx.__getitem__, reverse=True) for xx in (ll, rr))
	for i in range(len(xlat) - 1):
		while True:
			k = il[-1]
			lo = ll[k]
			if lo > i:
				break
			segments[k] = True
			for j in range(lo, rr[k]):
				mi[j] -= 1
				ma[j] -= 1
			del il[-1]
		x = max(ma) - min(mi)
		if res < x:
			res = x
			res_segments = segments[:]
		while True:
			k = ir[-1]
			hi = rr[k]
			if hi > i:
				break
			segments[k] = False
			for j in range(ll[k], hi):
				mi[j] += 1
				ma[j] += 1
			del ir[-1]
	print(res)
	segments = [i for (i, f) in enumerate(res_segments) if f]
	print(len(segments))
	print(*segments)

def __starting_point():
	main()
__starting_point()


import os
import sys
from io import BytesIO, IOBase

def main():
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	left = [[] for _ in range(n)]
	right = [[] for _ in range(n)]
	seg = []
	for _ in range(m):
		(l, r) = map(int, input().split())
		l -= 1
		r -= 1
		left[r].append(l)
		right[l].append(r)
		seg.append((l, r))
	dff = [0] * n
	ans = [-10 ** 10] * n
	mm = arr[0]
	for i in range(n):
		ans[i] = max(ans[i], arr[i] - mm)
		for l in left[i]:
			for j in range(l, i + 1):
				dff[j] -= 1
				mm = min(mm, arr[j] + dff[j])
		mm = min(mm, arr[i] + dff[i])
	dff = [0] * n
	mm = arr[n - 1]
	for i in range(n - 1, -1, -1):
		ans[i] = max(ans[i], arr[i] - mm)
		for r in right[i]:
			for j in range(i, r + 1):
				dff[j] -= 1
				mm = min(mm, arr[j] + dff[j])
		mm = min(mm, arr[i] + dff[i])
	final = max(ans)
	idx = ans.index(final)
	que = []
	for (i, item) in enumerate(seg):
		(l, r) = item
		if l <= idx <= r:
			continue
		que.append(i + 1)
	print(final)
	print(len(que))
	print(*que)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree2:

	def __init__(self, data, default=3000006, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 10, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor, t):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += t
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += t
		self.temp.data = pre_xor

	def query(self, p, l):
		ans = 0
		self.temp = self.root
		for i in range(31, -1, -1):
			val = p & 1 << i
			val1 = l & 1 << i
			if val1 == 0:
				if val == 0:
					if self.temp.left and self.temp.left.count > 0:
						self.temp = self.temp.left
					else:
						return ans
				elif self.temp.right and self.temp.right.count > 0:
					self.temp = self.temp.right
				else:
					return ans
			elif val != 0:
				if self.temp.right:
					ans += self.temp.right.count
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				else:
					return ans
			else:
				if self.temp.left:
					ans += self.temp.left.count
				if self.temp.right and self.temp.right.count > 0:
					self.temp = self.temp.right
				else:
					return ans
		return ans
(n, m) = map(int, input().split())
l = list(map(int, input().split()))
ma = max(l)
d = defaultdict(list)
d1 = defaultdict(list)
ans = [ma + m] * n
ans1 = [ma + m] * n
we = []
for i in range(m):
	(a, b) = map(int, input().split())
	we.append((a - 1, b - 1))
	d[b - 1].append(a - 1)
	d1[a - 1].append(b - 1)
e = l + []
for i in range(n):
	mi = e[i]
	ans[i] = mi
	if i > 0:
		for j in d[i - 1]:
			for k in range(j, i):
				e[k] -= 1
				mi = min(mi, e[k])
		ans[i] = min(ans[i - 1], mi)
e = l + []
for i in range(n - 1, -1, -1):
	mi = e[i]
	ans1[i] = mi
	if i < n - 1:
		for j in d1[i + 1]:
			for k in range(i + 1, j + 1):
				e[k] -= 1
				mi = min(mi, e[k])
		ans1[i] = min(ans1[i + 1], mi)
fi = 0
ind = -1
for i in range(n):
	if fi < l[i] - min(ans[i], ans1[i]):
		fi = l[i] - min(ans[i], ans1[i])
		ind = i
print(fi)
awe = []
for i in range(m):
	if we[i][1] < ind or we[i][0] > ind:
		awe.append(i + 1)
print(len(awe))
print(*awe)


(n, m) = map(int, input().split())
A = list(map(int, input().split()))
Lf = [[] for _ in range(n)]
Rb = [[] for _ in range(n)]
LR = []
for i in range(m):
	(l, r) = map(int, input().split())
	(l, r) = (l - 1, r - 1)
	Lf[r].append(l)
	Rb[l].append(r)
	LR.append((l, r))
minus = [0] * n
INF = 10 ** 18
ans = [-INF] * n
mn = A[0]
for i in range(n):
	ans[i] = max(ans[i], A[i] - mn)
	for l in Lf[i]:
		for j in range(l, i + 1):
			minus[j] -= 1
			mn = min(mn, A[j] + minus[j])
	mn = min(mn, A[i] + minus[i])
minus = [0] * n
mn = A[n - 1]
for i in reversed(range(n)):
	ans[i] = max(ans[i], A[i] - mn)
	for r in Rb[i]:
		for j in range(i, r + 1):
			minus[j] -= 1
			mn = min(mn, A[j] + minus[j])
	mn = min(mn, A[i] + minus[i])
ans_ = max(ans)
res = []
for i in range(n):
	if ans[i] == ans_:
		for j in range(m):
			(l, r) = LR[j]
			if not (l <= i and i <= r):
				res.append(j + 1)
		break
print(ans_)
print(len(res))
print(*res)


import sys
import copy
input = sys.stdin.readline
(n, m) = map(int, input().split())
A = list(map(int, input().split()))
LR = [list(map(int, input().split())) for i in range(m)]
MLIST = []
for (l, r) in LR:
	MLIST.append(l)
	MLIST.append(r)
MLIST = list(set(MLIST))
MLIST.sort()
MLIST.append(10 ** 9)
MDICT = dict()
MLEN = len(MLIST)
for i in range(MLEN):
	MDICT[MLIST[i]] = i
MINUSLIST = [[0] * (MLEN * 2 - 1) for i in range(MLEN)]
for (l, r) in LR:
	for j in range(MDICT[l], MDICT[r] + 1):
		for k in range(MDICT[l] * 2 + 1, MDICT[r] * 2 + 2):
			MINUSLIST[j][k] += 1
A_m = [[float('inf'), -float('inf')] for i in range(MLEN * 2 - 1)]
if MLIST[0] != 1:
	A_m[0] = [min(A[:MLIST[0] - 1]), max(A[:MLIST[0] - 1])]
for i in range(MLEN - 1):
	x = MLIST[i] - 1
	y = MLIST[i + 1] - 1
	A_m[2 * i + 1] = [A[x], A[x]]
	if x + 1 != y and x != n - 1:
		A_m[2 * i + 2] = [min(A[x + 1:y]), max(A[x + 1:y])]

def MINUS(A, B):
	MIN = float('inf')
	MAX = -float('inf')
	for i in range(MLEN * 2 - 1):
		if MIN > A[i][0] - B[i]:
			MIN = A[i][0] - B[i]
		if MAX < A[i][1] - B[i]:
			MAX = A[i][1] - B[i]
	return MAX - MIN
ANSLIST = [0] * MLEN
for i in range(MLEN):
	ANSLIST[i] = MINUS(A_m, MINUSLIST[i])
print(max(ANSLIST))
target = MLIST[ANSLIST.index(max(ANSLIST))]
AN = []
for i in range(m):
	(z, w) = LR[i]
	if z <= target <= w:
		AN.append(i + 1)
print(len(AN))
for a in AN:
	print(a, end=' ')


from sys import stdin
input = stdin.readline

def f(a, b):
	b = sorted(b, key=lambda s: s[1] - s[0])
	t = {}
	for i in range(len(a)):
		l = []
		for j in b:
			if i in range(j[0], j[1] + 1):
				l.append(j)
		t[i] = l
	t = dict(sorted(t.items(), key=lambda s: a[s[0]]))
	t = dict(sorted(t.items(), key=lambda s: len(s[1]) - a[s[0]], reverse=True))
	mn = list(t.items())[0]
	curr = max(a) - min(a)
	bigans = 0
	bigd = []
	for mn in t.items():
		s = a.copy()
		ans = []
		a2 = []
		for i in mn[1]:
			l = i[0]
			r = i[1]
			for j in range(l, r + 1):
				s[j] -= 1
			tempans = max(s) - min(s)
			if tempans >= curr:
				a2.append(i[2] + 1)
				ans += a2
				a2 = []
			else:
				a2.append(i[2] + 1)
			curr = max(curr, tempans)
		if bigans < curr:
			bigans = curr
			bigd = ans
		else:
			break
	return (bigd, bigans)
(a, b) = map(int, input().strip().split())
blacnk = []
lst = list(map(int, input().strip().split()))
for i in range(b):
	(l, r) = map(int, input().strip().split())
	blacnk.append([l - 1, r - 1, i])
x = f(lst, blacnk)
print(x[1])
print(len(x[0]))
print(*x[0])


from __future__ import division, print_function

def main():

	def f(a, b):
		b = sorted(b, key=lambda s: s[1] - s[0])
		t = {}
		for i in range(len(a)):
			l = []
			for j in b:
				if i in range(j[0], j[1] + 1):
					l.append(j)
			t[i] = l
		t = dict(sorted(t.items(), key=lambda s: a[s[0]]))
		t = dict(sorted(t.items(), key=lambda s: len(s[1]) - a[s[0]], reverse=True))
		mn = list(t.items())[0]
		curr = max(a) - min(a)
		bigans = 0
		bigd = []
		for mn in t.items():
			s = a.copy()
			ans = []
			a2 = []
			for i in mn[1]:
				l = i[0]
				r = i[1]
				for j in range(l, r + 1):
					s[j] -= 1
				tempans = max(s) - min(s)
				if tempans >= curr:
					a2.append(i[2] + 1)
					ans += a2
					a2 = []
				else:
					a2.append(i[2] + 1)
				curr = max(curr, tempans)
			if bigans < curr:
				bigans = curr
				bigd = ans
			else:
				break
		return (bigd, bigans)
	(a, b) = map(int, input().strip().split())
	blacnk = []
	lst = list(map(int, input().strip().split()))
	for i in range(b):
		(l, r) = map(int, input().strip().split())
		blacnk.append([l - 1, r - 1, i])
	x = f(lst, blacnk)
	print(x[1])
	print(len(x[0]))
	print(*x[0])
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()