Problem:


Score : 400 points

Problem Statement

There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.

Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town i (i < N), move to town i + 1.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.

Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

A_i are distinct.

2 ≦ T ≦ 10^9

In the initial state, Takahashi's expected profit is at least 1 yen.

Input

The input is given from Standard Input in the following format:

N T
A_1 A_2 ... A_N

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:

Move from town 1 to town 2.

Buy one apple for 50 yen at town 2.

Move from town 2 to town 3.

Sell one apple for 200 yen at town 3.

If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

10 100
7 10 4 5 9 3 6 8 2 1

Sample Output 3

2



Sample input:
3 2
100 50 200


Sample output:
1

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, T: int, A: "List[int]"):
    right_max = [0] * N # i番目よりあとで一番大きいA_i
    m_a = 0
    for i in range(1, N):
        m_a = max(m_a, A[-i])
        right_max[-i-1] = m_a

    m_p = 0
    count = 0
    for i, a in enumerate(A):
        profit = right_max[i] - a
        if profit > m_p:
            m_p = profit
            count = 1
        elif profit == m_p:
            count += 1
    print(count)
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    T = int(next(tokens))  # type: int
    A = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(N, T, A)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, t = map(int, input().split())
alist = list(map(int, input().split()))
minal = [alist[0]]
maxal = [alist[-1]]
for a in alist[1:]:
  if minal[-1] > a:
    minal.append(a)
  else:
    minal.append(minal[-1])

for a in alist[::-1][1:]:
  if maxal[-1] < a:
    maxal.append(a)
  else:
    maxal.append(maxal[-1])
maxal = maxal[::-1]

maxda = 0
ans = 0
prevmina, prevmaxa = None, None
for mina, maxa in zip(minal, maxal):
  if prevmina == mina and prevmaxa == maxa:
    continue
  elif maxa - mina == maxda:
    ans += 1
  elif maxa - mina > maxda:
    maxda = maxa - mina
    ans = 1
  prevmina, prevmaxa = mina, maxa

print(ans)

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
A = list(map(int, input().split()))
min_A = 1000000001
max_diff = 0
ans = 0
for i in A:
    min_A = min(min_A, i)
    if i - min_A == max_diff:
        ans += 1
    if i - min_A > max_diff:
        max_diff = i - min_A
        ans = 1
print(ans)

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
A = list(map(int, input().split()))
min_A = 1000000001
max_diff = 0
ans = 0
for i in A:
    min_A = min(min_A, i)
    if i - min_A == max_diff:
        ans += 1
    if i - min_A > max_diff:
        max_diff = i - min_A
        ans = 1
print(ans)

Submission status: Accepted

Solution code:
n,_,*a=map(int,open(0).read().split())
m=d=c=0
for t in a[::-1]:
    if t>m:
        m=t
    if m-t>d:
        d=m-t
        c=1
    elif m-t==d:
        c+=1
print(c)

Submission status: Accepted

Solution code:
n, t = map(int, input().split())
a = list(map(int, input().split()))

# print(a)

minv = a[0]

value = [0] * n
for i, v in enumerate(a[1:], 1):
    if minv >= v:
        value[i] = 0
        minv = v
    else:
        value[i] = v - minv

maxv = max(value)
# print(maxv)
print(value.count(maxv))

Submission status: Accepted

Solution code:
n, t = map(int, input().split())
ax = list(map(int, input().split()))
# iより後ろの売る中で最も高いもののリスト
sell = []
for a in ax[::-1][:n-1]:
    if len(sell) == 0:
        sell.append([a,1])
        continue
    if a > sell[-1][0]:
        sell.append([a,1])
    elif a == sell[-1][0]:
        sell.append([a, sell[-1][1]+1])
    else:
        sell.append(sell[-1])
sell = sell[::-1]
ans = {}
for i in range(n-1):
    sell_p, cnt = sell[i]
    ans[sell_p-ax[i]] = ans.get(sell_p-ax[i],0)+1
print(ans[max(ans.keys())])

Submission status: Accepted

Solution code:
N,T = map(int, input().split())
A = list(map(int, input().split()))

back = [(0,0)]*(N+1)
# (a,b): b is # of a
def heapsort(lst):
    h = []
    for value in lst:
        heappush(h,value)
    return [heappop(h) for i in range(len(h))]

for i in range(N, 0, -1):
    if A[i-1] > back[i][0]:
        back[i-1] = (A[i-1], 1)
    elif A[i-1] == back[i][0]:
        back[i-1] = (A[i-1], back[i][1] + 1)
    else:
        back[i-1] = back[i]

anslst = []
from heapq import heappush, heappop

for i in range(N):
    heappush(anslst, (- (back[i][0] - A[i]), back[i][1]) )
anslst = heapsort(anslst)


val = - anslst[0][0]

ans = 0
for i in range(N):
    if val != - anslst[i][0]:
        break
    ans += anslst[i][1] 
print(ans)

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
towns = list(map(int, input().split()))

p = towns[-1]
r = []

for i in reversed(range(N)):
    if towns[i] >= p:
        p = towns[i]
    else:
        r.append(p-towns[i])

res = r.count(max(r))
print(res)

Submission status: Accepted

Solution code:
#a
"""
import math
a, b = map(str, input().split())
j = int(a + b)
if math.sqrt(j).is_integer():
    print("Yes")
else:
    print("No")
"""

#b
"""
ans = ["Positive","Negative"]
a, b = map(int, input().split())
if 0 < a:
    print("Positive")
elif b >= 0:
    print("Zero")
else:
    print(ans[(b-a)%2-1])
"""

#C
"""
import itertools
n = int(input())
MARCH = ["M", "A", "R", "C", "H"]
march = [0 for _ in range(5)]
for i in range(n):
    s = input()
    if s[0] in MARCH:
        march[MARCH.index(s[0])] += 1
num = list(range(5))
a = list(itertools.combinations(num, 3))
ans = 0
for i in a:
    bf = 1
    for k in i:
        bf *= march[k]
    ans += bf
print(ans)
"""

#D
"""
n = int(input())
D = [list(map(int, input().split())) for _ in range(n)]
q = int(input())
p = [int(input()) for _ in range(q)]
ans = [[0 for i in range(n)] for _ in range(n)]
for i in range(n):
    for j in range(n):
        break
for _ in p:
    print(ans[p])
"""

#E
"""
s = input()
bf = s[0]
ans = 0
for i in range(1,len(s)):
    if bf != s[i]:
        ans += 1
        bf = s[i]
print(ans)
"""

#F
"""
n = int(input())
ta = [list(map(int, input().split())) for _ in range(n)]
ans = ta[0]
for i in ta:
    if ans[0] <= i[0] and ans[1] <= i[1]:
        ans = i
    else:
        a = ((ans[0] - 1) // i[0]) + 1
        b = ((ans[1] - 1) // i[1]) + 1
        ab = max(a,b)
        ans = [i[0] * ab, i[1] * ab]
print(ans[0]+ans[1])
"""

#G
n, t = map(int, input().split())
a = list(map(int, input().split()))
minv = a[0]
maxv = 0
ans = 0
for i in range(1, n):
    if maxv == a[i] - minv:
        ans += 1
    elif maxv < a[i] - minv:
        maxv = a[i] - minv
        ans = 1
    else:
        minv = min(minv,a[i])
print(ans)

#H
"""
s = input()
ans = 0
for i in range(1,len(s)):
    if i % 2 == 1:
        if s[i] != "p":
            ans += 1
    else:
        if s[i] != "g":
            ans -= 1
print(ans)
"""

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict
import math
def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()
def IIR(n): return [II() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
mod = 1000000007

#A
"""
a,b = LS()
c = int(a+b)
for i in range(1,1000):
    if i * i == c:
        print("Yes")
        quit()
print("No")
"""

#B
"""
a,b = LI()
if a*b <= 0:
    print("Zero")
else:
    if b < 0:
        if (a-b) %2 == 1:
            print("Positive")
        else:
            print("Negative")
    else:
        print("Positive")
"""

#C
"""
n = II()
s = SR(n)
march = [[] for i in range(5)]
ch = list("MARCH")
for i in s:
    for j in range(5):
        if i[0] == ch[j]:
            march[j].append(i)
ans = 0
for i in range(5):
    for j in range(i):
        for k in range(j):
            if len(march[i])*len(march[j])*len(march[k]) == 0:
                break
            ans += len(march[i])*len(march[j])*len(march[k])
print(ans)
"""

#D
"""
n = II()
d = LIR(n)
q = II()
p = IIR(q)
d.insert(0,[0 for i in range(n+1)])
for i in range(n):
    d[i+1].insert(0,0)
for i in range(n):
    for j in range(n):
        d[i+1][j+1] += d[i+1][j]+d[i][j+1]-d[i][j]
ans = [0 for i in range(n**2+1)]

for a in range(n+1):
    for b in range(n+1):
        for c in range(a):
            for e in range(b):
                ans[(a-c)*(b-e)] = max(ans[(a-c)*(b-e)],d[a][b]-d[c][b]-d[a][e]+d[c][e])

for i in p:
    an = 0
    for a in range(i+1):
        an = max(an, ans[a])
    print(an)
"""
#E

"""
s = list(S())
ans = -1
s.insert(0,0)
d = 0
for i in range(1,len(s)):
    if s[i] != d:
        d = s[i]
        ans += 1
print(ans)
"""

#F
"""
n = II()
x,y = LI()
for _ in range(n-1):
    a,b = LI()
    if a == b:
        x = max(x,y)
        y = x
    else:
        i = max(x//a,y//b)
        while 1:
            if a*i >= x and b*i >= y:break
            i += 1
        x = a*i
        y = b*i
print(x+y)
"""
#G
"""
s = list(S())
p = 0
g = 0
for i in s:
    if i == "g":
        g += 1
    else:
        p += 1
ans = (g-p)//2
print(ans)
"""
#H
n,t = LI()
a = LI()
b = []
for i in range(n):
    b.append([i,a[i]])
b.sort(key = lambda x:x[1])
b = b[::-1]
m = []
if n == 1:
    print(1)
    quit()
i = 0
for j in range(n):
    while i < b[j][0]:
        m.append(b[j][1])
        i += 1
ans = 0
ma = 0
for i in range(n-1):
    ma = max(ma,m[i]-a[i])
for i in range(n-1):
    if m[i]-a[i] == ma:
        ans += 1
print(ans)
#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T

Submission status: Accepted

Solution code:
n,t = map(int,input().split())
a = list(map(int,input().split()))

p = a[n-1]
r = []

for i in range(n-1,-1,-1):
    if a[i] >= p:
        p = a[i]
    else:
        r.append(p-a[i])

res = r.count(max(r))

print(res)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

sys.setrecursionlimit(10000)


N, T = (int(i) for i in input().split())
A = [int(i) for i in input().split()]

ma = A[-1]
mas = 1
resma = 0
rescc = 0
for i in range(N-2, -1 ,-1):
    if A[i] > ma:
        ma = A[i]
        mas = 1
    elif A[i] == ma:
        mas += 1
    else:
        if ma - A[i] > resma:
            resma = ma - A[i]
            rescc = 1
        elif ma - A[i] == resma:
            rescc += 1
        else:
            pass

print(rescc)

Submission status: Accepted

Solution code:
N,T=map(int,input().split())
A=list(map(int,input().split()))
i=0
j=1
a=0
b=0
while i<=N-1:
    if j==N:
        i=N
    elif A[i]>A[j]:
        i=j
        j+=1
    else:
        if A[j]-A[i]>a:
            a=A[j]-A[i]
            b=1
            j+=1
        elif A[j]-A[i]==a:
            b+=1
            j+=1
        elif A[j]-A[i]<a:
            j+=1
print(b)

Submission status: Accepted

Solution code:
N,T = map(int,input().split())
A = list(map(int,input().split()))

cummax = [A[-1]]
for a in reversed(A[:-1]):
    cummax.append(max(cummax[-1], a))
cummax.reverse()

maxgain = n = 0
for buy,sell in zip(A,cummax):
    gain = sell - buy
    if gain > maxgain:
        maxgain = gain
        n = 1
    elif gain == maxgain:
        n += 1
print(n)

Submission status: Accepted

Solution code:

def main():
    buf = input()
    buflist = buf.split()
    N = int(buflist[0])
    T = int(buflist[1])
    buf = input()
    buflist = buf.split()
    A = list(map(int, buflist))
    min_price = A[0]
    max_price_diff = 0
    max_diff_count = 0
    for i in range(1, N):
        if A[i] < min_price:
            min_price = A[i]
        elif A[i] - min_price > max_price_diff:
            max_price_diff = A[i] - min_price
            max_diff_count = 1
        elif A[i] - min_price == max_price_diff:
            max_diff_count += 1
    print(max_diff_count)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def inpl(): return [int(i) for i in input().split()]

N, T = inpl()
A = inpl()
minA = [0 for _ in range(N)]
minA[0] = A[0]
for i in range(N-1):
    minA[i+1] = min(minA[i], A[i+1]) 
ans = 1
maxpro = 0
for i in range(N-1):
    if A[i+1]-minA[i] == maxpro:
        ans += 1
    if A[i+1]-minA[i] > maxpro:
        ans = 1
        maxpro = A[i+1]-minA[i]

print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

N, T = map(int, input().split())
As = list(map(int, input().split()))

T //= 2
profits = [0] * (N - 1)
minA = As[0]
for i, A in enumerate(As[1:]):
    profits[i] = T * (A - minA)
    minA = min(minA, A)

cnts = Counter(profits)
print(cnts[max(cnts.keys())])

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
A = list(map(int, input().split()))

min_a = A[0]
profit = 0
ans = 0
for a in A[1:]:
    min_a = min(min_a, a)
    if a - min_a > profit:
        profit = a - min_a
        ans = 1
    elif a - min_a == profit:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

def main():
    n, t = map(int, input().split())
    an = list(map(int, input().split()))

    mi = [an[0]]
    for i in range(1, n):
        mi.append(min(mi[i - 1], an[i]))

    ma = 0
    num_ma = 0
    for i in range(1, n):
        be = an[i] - mi[i - 1]
        if be > ma:
            ma = be
            num_ma = 1
        elif be == ma:
            num_ma += 1
    print(num_ma)

main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

def main():
    n, t = map(int, input().split())
    an = list(map(int, input().split()))

    mi = [an[0]]
    se_mi = {0}
    for i in range(1, n):
        if mi[i - 1] > an[i]:
            se_mi = {i}
        elif mi[i - 1] == an[i]:
            se_mi.add(i)
        mi.append(min(mi[i - 1], an[i]))

    ma = 0
    se_ma = set()
    for i in range(1, n):
        be = an[i] - mi[i - 1]
        if be > ma:
            ma = be
            se_ma = {i}
        elif be == ma:
            se_ma.add(i)
    print(len(se_ma))

main()

Submission status: Accepted

Solution code:
f = lambda: map(int,input().split())
n,_ = f()
a = list(f())
b = [a[0]]+[0]*(n-1)
for i in range(1,n):
    b[i] = min(a[i], b[i-1])
c = [a[i]-b[i] for i in range(n)]
m = max(c)
print(c.count(m))

Submission status: Accepted

Solution code:
N,T=map(int,input().split())
A=[int(i) for i in input().split()]
B=[0 for i in range(N)]
B[0]=A[0]
for i in range(1,N):
    B[i]=min([B[i-1],A[i]])
C=[A[i]-B[i] for i in range(N)]
M=max(C)
ans=0
for i in range(N):
    if C[i]==M:
        ans+=1
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
N,T=map(int,input().split())
A=[int(i) for i in input().split()]
mi=A[0]
s=0
dd=defaultdict(int)
for i in range(1,N):
    mi=min(mi,A[i])
    s=max(A[i]-mi,s)
    dd[A[i]-mi]+=1
print(dd[s])

Submission status: Accepted

Solution code:
import numpy as np

N, T = np.array(input().split(), dtype="int")
A = np.array(input().split(), dtype="int")

max_num=A[-1]
num_dict = {}
for i in range(len(A)-1):
    ##print(A[-i-1],max_num - A[-i-2],num_dict)
    if(A[-i-1]>max_num):
        max_num=A[-i-1]
    if(max_num > A[-i-2]):
        if(max_num - A[-i-2] in num_dict):
            num_dict[max_num - A[-i-2]] +=1
        else:
            num_dict[max_num - A[-i-2]]=1
key = max(num_dict.keys())
print(num_dict[key])

Submission status: Accepted

Solution code:
n,t = map(int,raw_input().split())

arr = map(int,raw_input().split())

mintable = []
m = float("inf")
for i in arr :
	mintable.append(min(m,i))
	m = min(m,i)

ma = float("-inf")
for i in range(n):
	ma = max(ma,arr[i] - mintable[i])
ans = 0
for i in range(n):
	if arr[i] - mintable[i] == ma:	
		ans += 1

print ans

Submission status: Accepted

Solution code:
n=int(input().split()[0])
s=input().split()
l=[0 for i in range(n)]
m=[0 for i in range(n)]
M=[0 for i in range(n)]
for i in range(n):
  l[i]=int(s[i])
m[0]=l[0]
M[0]=l[-1]
for i in range(1,n):
  m[i]=min(m[i-1],l[i])
  M[i]=max(M[i-1],l[-i-1])
M.reverse()
d=[M[i]-m[i] for i in range(n)]
ma=max(d)
memo=-1
cnt=0
for i in range(n):
   if d[i]==ma and m[i]!=memo:
      cnt+=1
      memo=m[i]
print(cnt)

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
A = list(map(int, input().split()))

low = [A[0]]
high = [A[N-1]]
for i in range(1, N):
    low.append(min(A[i], low[i-1]))
for i in reversed(range(N-1)):
    high.append(max(A[i], high[N-2-i]))

high.reverse()
max_gap = max([high[i] - low[i] for i in range(N)])
num = 0
first = True
for i in range(N):
    if high[i] - low[i] == max_gap:
        if first:
            idx = i
            num += 1
            first = False
        else:
            if low[idx] != low[i]:
                idx = i
                num += 1

print(num)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
def inpl(): return map(int, input().split())
N, T = inpl()
A = tuple(inpl())
m = A[0]
benefit = 0
pairs = 0
ans = 0

for i in range(1, N):
    a = A[i]
    d = a - m
    if d < 0:
        m = a
    elif d < benefit:
        continue
    elif d == benefit:
        pairs += 1
    elif d > benefit:
        ans = max(ans, pairs)
        benefit = d
        pairs = 1

ans = max(ans, pairs)
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
N, T = map(int, input().split())

cost_list = np.array(list(map(int, input().split())))

max_num = 0
max_profit = 0
max_list = []
max_value = 0
for x in reversed(cost_list[1:]):
    max_value = max(max_value, x)
    max_list.append(max_value)
max_list = list(reversed(max_list))
max_list = np.array(max_list)
res = max_list - cost_list[:-1]

res_max = max(res)

max_num_list = [y for y in res if y == res_max]

print(len(max_num_list))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

N, T = map(int, input().split())
A = list(map(int, input().split()))

d = 0
ans = 1
l = A[0]
for a in A[1:]:
    l = min(l, a)
    r = a
    if r - l == d:
        ans += 1
    elif r - l > d:
        ans = 1
        d = r - l

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)


class Segtree():
    INT_MIN=-10**9

    def __init__(self,size):
        self.size=1
        while self.size<size:
            self.size=self.size*2
        self.node=[self.INT_MIN]*(2*self.size-1)


    def update(self,k,a):
        k+=self.size-1
        self.node[k]=a
        while k>0:
            k=(k-1)/2
            self.node[k]=max(self.node[k*2+1],self.node[k*2+2])

    def get_max(self,queryL,queryR,k=0,nodeL=0,nodeR=-1):
        if nodeR==-1:nodeR=self.size
        if (nodeR<=queryL or queryR<=nodeL):return self.INT_MIN
        if (queryL<=nodeL and nodeR<=queryR):return self.node[k]
        else:
            nodeM=(nodeL+nodeR)/2
            vl=self.get_max(queryL,queryR,k*2+1,nodeL,nodeM)
            vr=self.get_max(queryL,queryR,k*2+2,nodeM,nodeR)
            return max(vl,vr)

n,t=map(int,raw_input().split())
a=map(int,raw_input().split())
seg=Segtree(n)
for i in xrange(n):
    seg.update(i,a[i])
ans=0
mx=0
for i in xrange(n):
    tmp=seg.get_max(i,n)-a[i]
    if mx<tmp:
        ans=1
        mx=tmp
    elif mx==tmp:
        ans+=1
print ans

Submission status: Accepted

Solution code:
n,t=map(int,raw_input().split())
a=map(int,raw_input().split())
pos={}
mx=[0]*(n+1)
for i in xrange(n-1,-1,-1):
    mx[i]=max(mx[i+1],a[i])
for i in xrange(n):
    pos[a[i]]=i
a.sort()
ans=0
b=0
for i in xrange(n):
    idx=pos[a[i]]
    if b<mx[idx]-a[i]:
        b=mx[idx]-a[i]
        ans=1
    elif b==mx[idx]-a[i]:
        ans+=1
print ans

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
A = list(map(int, input().split()))

diff = -1
mini = A[0]
cnt = 0
ans = 0

for i in range(1, N):
	now = A[i]

	if mini > now:
		mini = now
	else:
		if now - mini == diff:
			cnt += 1
		elif now - mini > diff:
			diff = now - mini
			ans = max(ans, cnt)
			cnt = 1
ans = max(ans, cnt)
print(ans)

Submission status: Accepted

Solution code:
N, T = map(int, raw_input().split())
A = map(int, raw_input().split())

X = [0]*N
for i in xrange(N - 2, -1, -1):
    X[i] = max(X[i + 1], A[i + 1])

mx, cnt = 0, 0
for i, a in enumerate(A):
    tmp = X[i]
    if tmp - a > mx:
        mx = tmp - a
	cnt = 1
    elif tmp - a == mx:
        cnt += 1
print cnt

Submission status: Accepted

Solution code:
#D    高橋君と見えざる手 / An Invisible Hand
N,T = [int(i) for i in input().split(" ")]
A=[int(i) for i in input().split(" ")]
Max = 0
count = 1
Min = A[0]
for i in range(N):
    if A[i] <= Min :
        Min = A[i]
    else :
        temp = A[i]-Min
        if temp > Max:
            Max = temp 
            count = 1
        elif temp == Max :
            count += 1
print(count)

Submission status: Accepted

Solution code:
from numpy import *
input()
a=array(input().split(),dtype=int)
d=a-minimum.accumulate(a)
print((d==d.max()).sum())

Submission status: Accepted

Solution code:
import numpy as np

input()
a = np.array(input().split(), dtype=np.int)

diff = a - np.minimum.accumulate(a)
print((diff == diff.max()).sum())

Submission status: Accepted

Solution code:
import unittest

class TestFunc(unittest.TestCase):
    def test_1(self):
        self.assertEqual(fun(5,8,[50,30,40,10,20]),2)
	self.assertEqual(fun(3,2,[100,50,200]),1)
        self.assertEqual(fun(10,100,[7,10,4,5,9,3,6,8,2,1]),2)
        self.assertEqual(fun(5,2,[1,2,3,2,4]),1)

def fun(n,t,a):
    aa = []
    b = None
    s = None
    for i in range(n):
	if b!=None:
            if s==None:
		if b<a[i]:
                    s = a[i]
                else:
                    b = a[i]
            elif s<=a[i]:
                s = a[i]
            elif s>b:
                aa.append(s-b)
		if b>a[i]:
                    b = a[i]
		s = None
	else:
            b = a[i]

    if b!=None and s!= None and s-b>0:
	aa.append(s-b)

    c = aa[0]
    ans = 1
    for i in range(1,len(aa)):
	if c<aa[i]:
            c = aa[i]
            ans = 1
	elif c==aa[i]:
            ans += 1

    return ans


if __name__=='__main__':
    #unittest.main()                                                                                                                                                              

    n,t = [int(x) for x in raw_input().split(" ")]
    a = [int(x) for x in raw_input().split(" ")]
    print(fun(n,t,a))

Submission status: Accepted

Solution code:
input_lines = input()
items = input_lines.split()
N = int(items[0])
T = int(items[1])

input_lines = input()
items = input_lines.split()
As = [int(x) for x in items]

def my_func(N, T, As):
    buys = T // 2
    counts = 0
    val_earn = 0
    val_min = 10E10
    for val in As:
        if val < val_min:
            val_min = val
        else:
            diff = val - val_min
            if diff == val_earn:
                counts += 1
            elif diff > val_earn:
                val_earn = diff
                counts = 1
    print(counts)

my_func(N, T, As)

Submission status: Accepted

Solution code:
# f = open('input', 'r')
# n, t = map(int, f.readline().split())
# A = list(map(int, f.readline().split()))
n, t = map(int, input().split())
A = list(map(int, input().split()))

ans = 0
max_diff = 0
min_a = A[0]
for a in A:
    min_a = min(min_a, a)
    if (a - min_a) == max_diff:
        ans += 1
    elif (a - min_a) > max_diff:
        ans = 1
        max_diff = (a - min_a)
print(ans)

Submission status: Accepted

Solution code:
def main():
    N, T = [int(x) for x in input().split()]
    price = [int(x) for x in input().split()]

    minprice = 1000000000;
    maxbenefit = 0
    dict = {}
    res = 0

    for i in range(len(price)):
        if (price[i] < minprice): minprice = price[i]
        if (maxbenefit < (price[i] - minprice)): maxbenefit = (price[i] - minprice)
        dict[price[i]] = i

    for i in range(len(price)):
        if price[i] + maxbenefit in dict:
            if (dict[price[i] + maxbenefit] > i): res += 1

    print(res)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import numpy as np

if __name__ == "__main__":
	n,t = map(int,raw_input().split())
	li = map(int,raw_input().split())

	minv = li[0]
	dm = 0
	ans = 1
	for i in range(1, len(li)):
		minv = min(minv, li[i])
		if(dm == li[i] - minv):
			ans += 1
		elif(dm < li[i]-minv):
			dm = li[i] - minv
			ans = 1

	print ans

Submission status: Accepted

Solution code:
#! /usr/bin/env python3

N, T = map(int, input().split())
A = list(map(int, input().split()))
p = -1
dif = h = hc = lc = c = 0
for i in A[-2::-1]:
    a, b = A[p], A[p]-i
    if i > a:
        p = -c-2
    elif b >= dif:
        if a != h : h, hc = a, hc+1
        if b > dif : dif, lc = b, 0
        lc += 1
    c += 1
print(min(hc, lc))

Submission status: Accepted

Solution code:
input()
a = [int(x) for x in input().split()]

lowest = a[0]
lowests = {a[0]}
diff = -1
pairs = []

for x in a[1:]:
    if lowest > x:
        lowests = {x}
        lowest = x
    elif lowest == x:
        lowests.add(x)
    elif diff == x - lowest:
        pairs += [(x, y) for y in lowests]
    elif diff < x - lowest:
        pairs = [(x, y) for y in lowests]
        diff = x - lowest

a, b = zip(*pairs)
print(min(len(set(a)), len(set(b))))

Submission status: Accepted

Solution code:
N, T = map(int, raw_input().split())
A_n = map(int, raw_input().split())

count = 0
max_profit = A_n[1] - A_n[0]
min_element = min(A_n[0], A_n[1])
for i in xrange(1, len(A_n)):
    if A_n[i] - min_element > max_profit:
        max_profit = A_n[i] - min_element
        count = 0

    if A_n[i] - min_element == max_profit:
        count += 1

    if A_n[i] < min_element:
        min_element = A_n[i]

print count

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
a = [int(i) for i in input().split()]
b = [a[0]]
m = b[0]
for i in range(1,N):
	if m > a[i]:
		m = a[i]
	b.append(m)
c = [a[i] - b[i] for i in range(N)]
print(c.count(max(c)))

Submission status: Accepted

Solution code:
#! /usr/bin/env python3

N, T = map(int, input().split())
A = list(map(int, input().split()))
pu = -1
SPU = set([])
SPD = []
b = 0
c = 0
for i in A[:-1][::-1]:
    if i > A[pu]:
        pu = -c-2
    elif i < A[pu] and A[pu]-i >= b:
        SPU.add(pu)
        b = A[pu]-i
        SPD += [b]
    c += 1

print(min(len(SPU), SPD.count(b)))

Submission status: Accepted

Solution code:
from sys import stdin
input = stdin.readline
N,T = map(int,input().split())
prices = list(map(int,input().split()))
last = 10000000000
highestTally = [prices[-1]]
highestCount = [1]

for price in prices[-2:-N-1:-1]:
    if price==highestTally[-1]:
        highestCount.append(highestCount[-1]+1)
    else:
        highestCount.append(1)
    highestTally.append(max(highestTally[-1],price))
highestTally.reverse()
highestCount.reverse()

indexOfHighest={}
for i in range(N-1,-1,-1):
    if highestTally[i]==prices[i]:
        indexOfHighest[highestTally[i]]=i

biggestJump=0
sellingPriceForBiggestJump=0
HPcount=0
LPcount=0
HPGroups=[]
LPGroups=[]
for index,price in enumerate(prices):
    if index==N-1:
        break
    bestSellingPrice = highestTally[index+1]
    jump = bestSellingPrice-price
    #print(jump,bestSellingPrice,biggestJump)
    if jump>biggestJump:
        biggestJump = jump
        #LPcount+=1
        LPGroups=[]
        HPGroups=[]
        
        LPGroups.append(1)
        sellingPriceForBiggestJump = bestSellingPrice
        #HPcount=highestCount[indexOfHighest[bestSellingPrice]]
        HPGroups.append(highestCount[indexOfHighest[bestSellingPrice]])
    elif jump==biggestJump:
        if bestSellingPrice!=sellingPriceForBiggestJump:
            sellingPriceForBiggestJump = bestSellingPrice
            #HPcount+=highestCount[indexOfHighest[bestSellingPrice]]
            HPGroups.append(highestCount[indexOfHighest[bestSellingPrice]])
            LPGroups.append(0)
        LPGroups[-1]+=1
count = 0
bs = T//2
for a,b in zip(HPGroups,LPGroups):
    if bs>min(a,b):
        count+=min(a,b)
    else:
        count+=bs
print(count)

Submission status: Accepted

Solution code:
n, t = map(int, raw_input().split())
prices = list(map(int, raw_input().split()))
lows = n * [ 0 ]
low = prices[0] + 1
for i, x in enumerate(prices):
    if x < low:
        low = x
    lows[i] = x
best_gap = 0
best_gap_count = 0
high = prices[-1] - 1
low = lows[-2] + 1
for i in range(len(prices) - 1, 0, -1):
    update = False
    x = prices[i]
    if x > high:
        high = x
        update = True
    if lows[i - 1] != low:
        low = lows[i - 1]
        update = True
    if update:
        gap = high - low
        if gap == best_gap:
            best_gap_count += 1
        elif gap > best_gap:
            best_gap = gap
            best_gap_count = 1
print(best_gap_count)

Submission status: Accepted

Solution code:
#!/usr/bin/env pypy3

import collections


INF = 10 ** 10


def solve(n, t, xs):
    trades = collections.Counter()
    maxs = [INF for _ in range(n)]
    maxs[n - 1] = xs[n - 1]
    for i in range(n - 1)[::-1]:
        maxs[i] = max(xs[i], maxs[i + 1])
    for i in range(n):
        delta = maxs[i] - xs[i]
        if delta > 0:
            trades[delta] += 1
    max_delta = max(trades.keys())
    return trades[max_delta]


def main():
    n, t = map(int, input().split())
    xs = list(map(int, input().split()))
    print(solve(n, t, xs))


if __name__ == '__main__':
    main()