Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.

She starts with 0 money on her account.

In the evening of i-th day a transaction a_{i} occurs. If a_{i} > 0, then a_{i} bourles are deposited to Luba's account. If a_{i} < 0, then a_{i} bourles are withdrawn. And if a_{i} = 0, then the amount of money on Luba's account is checked.

In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.

It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be «-1».

Luba must not exceed this limit, and also she wants that every day her account is checked (the days when a_{i} = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!


-----Input-----

The first line contains two integers n, d (1 ≤ n ≤ 10^5, 1 ≤ d ≤ 10^9) —the number of days and the money limitation.

The second line contains n integer numbers a_1, a_2, ... a_{n} ( - 10^4 ≤ a_{i} ≤ 10^4), where a_{i} represents the transaction in i-th day.


-----Output-----

Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.


-----Examples-----
Input
5 10
-1 5 0 -5 3

Output
0

Input
3 4
-10 0 20

Output
-1

Input
5 10
-5 0 10 -11 0

Output
2

Difficulty: HARD
Tags: Dynamic programming

Data structures

Implementation

Greedy algorithms
Skill types: Dynamic programming

Data structures

Greedy algorithms

Starter code:

Solutions:
(n, d) = map(int, input().split())
a = [0] + list(map(int, input().split()))
b = [0] * (n + 2)
b[n] = a[n]
now = a[n]
for i in range(n - 1, 0, -1):
	now = a[i] + max(now, 0)
	b[i] = now
now = 0
res = 0
for i in range(1, n + 1):
	if a[i] == 0:
		if now < 0:
			res += 1
			now = min(d, max(0, d - b[i + 1]))
	else:
		now += a[i]
		if now > d:
			res = -1
			break
print(res)


(n, d) = map(int, input().split())
a = list(map(int, input().split()))
pref = [0 for i in range(n)]
c = 0
for i in range(n):
	c += a[i]
	if a[i] == 0:
		c = max(0, c)
	pref[i] = c
suff = [0 for i in range(n)]
suff[-1] = pref[-1]
mc = suff[-1]
for i in range(n - 2, -1, -1):
	suff[i] = max(mc, pref[i])
	mc = suff[i]
	if a[i] == 0 and i > 0:
		mc = pref[i - 1]
if max(suff) > d:
	print(-1)
	return
c = 0
ans = 0
for i in range(n):
	if a[i] != 0:
		c += a[i]
	elif c < 0:
		ans += 1
		c = max(0, c)
		c += d - suff[i]
print(ans)


def main():
	(n, d) = map(int, input().split())
	a = list(map(int, input().split()))
	(pref, mx, add, ans) = ([0] * n, [0] * n, 0, 0)
	for pos in range(n):
		pref[pos] = a[pos] if not pos else a[pos] + pref[pos - 1]
	for pos in range(n - 1, -1, -1):
		mx[pos] = pref[pos] if pos == n - 1 else max(mx[pos + 1], pref[pos])
	for i in range(n):
		if pref[i] + add > d:
			print('-1')
			return
		if a[i] == 0 and pref[i] + add < 0:
			ans += 1
			add += max(-(pref[i] + add), d - mx[i] - add)
	print(ans)

def __starting_point():
	main()
__starting_point()


(n, d) = list(map(int, input().split()))
l = list(map(int, input().split()))
mus = [0] * n
mus[0] = l[0]
cnt = 0
ans = 0
for i in range(1, n):
	mus[i] = mus[i - 1] + l[i]
suf = [0] * n
suf[-1] = mus[-1]
for i in range(n - 2, -1, -1):
	suf[i] = max(mus[i], suf[i + 1])
for i in range(n):
	if l[i] == 0 and mus[i] + cnt < 0:
		if d - suf[i] - cnt < 0 or d - suf[i] < abs(mus[i]):
			print(-1)
			return
		else:
			cnt += d - suf[i] - cnt
			ans += 1
if suf[0] > d:
	print(-1)
	return
print(ans)


(H, L, t) = (0, 0, 0)
(n, d) = map(int, input().split())
for i in map(int, input().split()):
	if i == 0:
		if H < 0:
			H = d
			t += 1
		L = max(L, 0)
	L += i
	H = min(d, H + i)
	if L > d:
		print(-1)
		return ()
print(t)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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 SegmentTree1:

	def __init__(self, data, default=2 ** 51, 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 SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(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
(n, d) = map(int, input().split())
l = list(map(int, input().split()))
m = [-10 ** 10] * n
bal = 0
ans = 0
for i in range(n - 1, -1, -1):
	if l[i] != 0:
		bal += l[i]
	if bal <= 0:
		bal = 0
	m[i] = max(bal, m[i])
bal = 0
for i in range(n):
	if l[i] != 0:
		bal += l[i]
		if bal > d:
			print(-1)
			sys.exit(0)
	elif bal >= 0:
		continue
	elif m[i] > d:
		print(-1)
		sys.exit(0)
	else:
		ans += 1
		bal = d - m[i]
print(ans)


import sys, math, queue, bisect
MOD = 10 ** 9 + 7
sys.setrecursionlimit(1000000)
(n, d) = map(int, input().split())
a = list(map(int, input().split()))
p = [0 for i in range(n)]
for i in range(n):
	p[i] = p[i - 1] + a[i]
mx = [-1 for i in range(n)]
mx[-1] = p[-1]
for i in range(n - 2, -1, -1):
	mx[i] = max(mx[i + 1], p[i])
c = 0
ans = 0
for i in range(n):
	p[i] += c
	if p[i] > d:
		print(-1)
		exit()
	if a[i] != 0 or p[i] >= 0:
		continue
	av = d - (mx[i] + c)
	if -p[i] > av:
		print(-1)
		exit()
	ans += 1
	c = d - mx[i]
print(ans)


(n, d) = [int(x) for x in input().split()]
tr = [int(x) for x in input().split()]
cash = 0
flag = False
gr = []
for i in tr:
	if i != 0:
		cash += i
	gr.append(cash)
	if cash > d:
		flag = True
		break
if flag:
	print(-1)
else:
	mx = [-1] * n
	mx[-1] = gr[-1]
	for i in range(n - 2, -1, -1):
		mx[i] = max(gr[i], mx[i + 1])
	acash = 0
	count = 0
	for i in range(n):
		if tr[i] == 0:
			if gr[i] + acash < 0:
				acash += d - mx[i] - acash
				if gr[i] + acash < 0:
					count = -1
					break
				count += 1
	print(count)


R = lambda : map(int, input().split())
(n, k) = R()
arr = list(R())
tup = [0, 0]
res = 0
for x in arr:
	if x != 0:
		(tup[0], tup[1]) = (tup[0] + x, tup[1] + x)
		tup[1] = min(tup[1], k)
	elif tup[1] < 0:
		(tup[0], tup[1]) = (0, k)
		res += 1
	else:
		tup[0] = max(0, tup[0])
	if tup[0] > k:
		res = -1
		break
print(res)


import sys
input = sys.stdin.readline
(n, d) = list(map(int, input().split()))
a = list(map(int, input().split()))
ans = 0
(ub, lb) = (0, 0)
for x in a:
	if x == 0:
		if ub < 0:
			(ub, lb) = (d, 0)
			ans += 1
		if lb < 0:
			lb = 0
	else:
		ub = min(d, ub + x)
		lb += x
		if lb > d:
			print(-1)
			return
print(ans)


[n, d] = [int(x) for x in input().split(' ')]
A = [int(a) for a in input().split(' ')]

def solve():
	ans = 0
	bal = 0
	minGap = 0
	for i in range(n):
		if A[i] == 0:
			if bal < 0:
				go = min(-bal, minGap)
				minGap -= go
				bal += go
				if bal < 0:
					ans += 1
					bal = 0
					minGap = d
		else:
			bal += A[i]
			if bal > d:
				return -1
			minGap = min(minGap, d - bal)
	return ans
print(solve())


(n, d) = list(map(int, input().split()))
a = list(map(int, input().split()))
s = 0
m = 0
ans = 0
flag = True
n = len(a)
for i in range(n):
	if a[i] == 0:
		if s < 0:
			s = d
			m = d
			ans += 1
		else:
			m = min(m, s)
	elif a[i] < 0:
		s = s + a[i]
	elif s + a[i] > d:
		if s + a[i] - d > m:
			flag = False
			break
		else:
			m -= s + a[i] - d
			s = d
	else:
		s = s + a[i]
if flag:
	print(ans)
else:
	print(-1)


import sys
(n, d) = map(int, input().split())
a = list(map(int, input().split()))
(ub, lb) = (0, 0)
ans = 0
for x in a:
	if x == 0:
		if ub < 0:
			(ub, lb) = (d, 0)
			ans += 1
		lb = max(lb, 0)
	else:
		ub = min(d, ub + x)
		lb += x
		if lb > d:
			print(-1)
			exit()
print(ans)


(n, d) = map(int, input().split())
line = list(map(int, input().split()))
pref = [0] * n
maxx = 0
for i in range(n):
	pref[i] = pref[max(i - 1, 0)] + line[i]
	maxx = max(maxx, pref[i])
maxr = [0] * n
for i in range(n - 1, -1, -1):
	if i == n - 1:
		maxr[i] = pref[i]
	else:
		maxr[i] = max(maxr[i + 1], pref[i])
sm = 0
bon = 0
ans = 0
b = True
if maxx > d:
	b = False
for i in range(n):
	elem = line[i]
	sm += elem
	if elem == 0:
		if sm + bon < 0:
			ans += 1
			bon += max(0, d - (maxr[i] + bon))
		if sm + bon < 0:
			b = False
			break
	if sm + bon > d:
		b = False
		break
if b == False:
	print(-1)
else:
	print(ans)


import os
import sys

def log(*args, **kwargs):
	if os.environ.get('CODEFR'):
		print(*args, **kwargs)
(n, d) = tuple(map(int, input().split()))
a = list(map(int, input().split()))
s = 0
k = 0
dep = 0
for i in a:
	if i == 0:
		if s < 0:
			if dep < -s:
				k += 1
				dep = d
			else:
				dep += s
			s = 0
	else:
		s += i
		if s > d:
			print(-1)
			sys.exit(0)
		dep = min(dep, d - s)
print(k)


f = lambda : map(int, input().split())
(n, d) = f()
h = s = k = 0
for q in f():
	(h, s) = (h + q, min(d, s + q))
	if h > d:
		k = -1
		break
	if q == 0:
		h = max(0, h)
		if s < 0:
			(s, k) = (d, k + 1)
print(k)


import sys
from random import *
from bisect import *
pl = 1
from math import gcd, sqrt
from copy import *
sys.setrecursionlimit(10 ** 5)
if pl:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('outpt.txt', 'w')

def li():
	return [int(xxx) for xxx in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())
t = 1
ans = []
time = flag = 1
d = {}
while t > 0:
	t -= 1
	(n, d) = mi()
	a = li()
	p = []
	for i in range(n):
		if a[i] == 0:
			p.append(i)
	c = ans = 0
	nex = n
	r = [0] * n
	for i in range(len(p) - 1, -1, -1):
		j = p[i] + 1
		c = maxi = 0
		while j < nex:
			c += a[j]
			maxi = max(maxi, c)
			j += 1
		if i == len(p) - 1:
			r[p[i]] = max(0, d - maxi)
		else:
			r[p[i]] = max(0, min(r[nex] - c, d - maxi))
		nex = p[i]
	c = 0
	for i in range(n):
		if a[i] == 0:
			if c < 0:
				ans += 1
				c = r[i]
		else:
			c += a[i]
		if c > d:
			print(-1)
			exit(0)
	print(ans)


import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
(N, D) = map(int, input().split())
A = [int(x) for x in input().split()]
presum = [0] * (N + 1)
for i in range(1, N + 1):
	presum[i] = presum[i - 1] + A[i - 1]
rightmax = [0] * N
mx = float('-inf')
for i in range(N - 1, -1, -1):
	mx = max(mx, presum[i + 1])
	rightmax[i] = mx
if any((v > D for v in presum)):
	print(-1)
	return
ans = 0
added = 0
for i in range(N):
	if A[i] == 0:
		if presum[i + 1] + added < 0:
			dmin = 0 - presum[i + 1] - added
			dmax = min(D - presum[i + 1] - added, D - added - rightmax[i])
			if dmin > dmax:
				print(-1)
				return
			added += dmax
			ans += 1
print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
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 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 SegmentTree1:

	def __init__(self, data, default=10 ** 6, 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)
MOD = 10 ** 9 + 7

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
mod = 10 ** 9 + 7
omod = 998244353

class LazySegTree:

	def __init__(self, _op, _e, _mapping, _composition, _id, v):

		def set(p, x):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			_d[p] = x
			for i in range(1, _log + 1):
				_update(p >> i)

		def get(p):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			return _d[p]

		def prod(l, r):
			assert 0 <= l <= r <= _n
			if l == r:
				return _e
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r >> i)
			sml = _e
			smr = _e
			while l < r:
				if l & 1:
					sml = _op(sml, _d[l])
					l += 1
				if r & 1:
					r -= 1
					smr = _op(_d[r], smr)
				l >>= 1
				r >>= 1
			return _op(sml, smr)

		def apply(l, r, f):
			assert 0 <= l <= r <= _n
			if l == r:
				return
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r - 1 >> i)
			l2 = l
			r2 = r
			while l < r:
				if l & 1:
					_all_apply(l, f)
					l += 1
				if r & 1:
					r -= 1
					_all_apply(r, f)
				l >>= 1
				r >>= 1
			l = l2
			r = r2
			for i in range(1, _log + 1):
				if l >> i << i != l:
					_update(l >> i)
				if r >> i << i != r:
					_update(r - 1 >> i)

		def _update(k):
			_d[k] = _op(_d[2 * k], _d[2 * k + 1])

		def _all_apply(k, f):
			_d[k] = _mapping(f, _d[k])
			if k < _size:
				_lz[k] = _composition(f, _lz[k])

		def _push(k):
			_all_apply(2 * k, _lz[k])
			_all_apply(2 * k + 1, _lz[k])
			_lz[k] = _id
		_n = len(v)
		_log = _n.bit_length()
		_size = 1 << _log
		_d = [_e] * (2 * _size)
		_lz = [_id] * _size
		for i in range(_n):
			_d[_size + i] = v[i]
		for i in range(_size - 1, 0, -1):
			_update(i)
		self.set = set
		self.get = get
		self.prod = prod
		self.apply = apply
MIL = 1 << 20

def makeNode(total, count):
	return total * MIL + count

def getTotal(node):
	return math.floor(node / MIL)

def getCount(node):
	return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)

def nodeOp(node1, node2):
	return node1 + node2
	return makeNode(getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2))
identityMapping = -1

def mapping(tag, node):
	if tag == identityMapping:
		return node
	count = getCount(node)
	return makeNode(tag * count, count)

def composition(mapping1, mapping2):
	return mapping1 if mapping1 != identityMapping else mapping2
prime = [True for i in range(10)]
pp = [0] * 10

def SieveOfEratosthenes(n=10):
	p = 2
	c = 0
	while p * p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				pp[i] += 1
				prime[i] = False
		p += 1

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

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[0]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = arr[mid]
			left = mid + 1
	return res
t = 1
s = Combination(mod)
for _ in range(t):
	(n, d) = map(int, input().split())
	a = list(map(int, input().split()))
	m = d
	c = 0
	res = 0
	check = 1
	for i in a:
		if i == 0:
			if c > 0:
				continue
			req = abs(min(0, c))
			if req > d - m:
				m = 0
				res += 1
				c = 0
			else:
				m += req
				c = 0
		else:
			c += i
			m = max(m, c)
			if c > d:
				check = 0
				break
	if check:
		print(res)
	else:
		print(-1)


(n, d) = map(int, input().split())
a = list(map(int, input().split()))
f = True
b = [a[0]]
for i in range(1, n):
	b.append(b[i - 1] + a[i])
if max(b) > d:
	f = False
h = [0] * n
h[n - 1] = b[n - 1]
for i in range(n - 2, -1, -1):
	h[i] = max(b[i], h[i + 1])
(x, k) = (0, 0)
for i in range(n):
	if a[i] == 0 and b[i] + x < 0:
		k += 1
		x += d - (h[i] + x)
		if b[i] + x < 0:
			f = False
			break
if f:
	print(k)
else:
	print(-1)