Problem:


Score : 100 points

Problem Statement

Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.

The vacation consists of N days.
For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:

A: Swim in the sea. Gain a_i points of happiness.

B: Catch bugs in the mountains. Gain b_i points of happiness.

C: Do homework at home. Gain c_i points of happiness.

As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.

Find the maximum possible total points of happiness that Taro gains.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq a_i, b_i, c_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the maximum possible total points of happiness that Taro gains.

Sample Input 1

3
10 40 70
20 50 80
30 60 90

Sample Output 1

210

If Taro does activities in the order C, B, C, he will gain 70 + 50 + 90 = 210 points of happiness.

Sample Input 2

1
100 10 1

Sample Output 2

100

Sample Input 3

7
6 7 8
8 8 3
2 5 2
7 8 6
4 6 8
2 3 4
7 5 1

Sample Output 3

46

Taro should do activities in the order C, A, B, A, C, B, A.



Sample input:
3
10 40 70
20 50 80
30 60 90


Sample output:
210

Submission status: Runtime Error

Solution code:
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College
    Date:11/06/2020

'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

def dp(idx,f,a,cache):
    if idx==len(a):
        return 0
    if cache[idx][f]!=-1:
        return cache[idx][f]
    ans=0
    for i in range(3):
        if i==f:
            continue
        ans=max(ans,dp(idx+1,i,a,cache))
    ans+=a[idx][f]
    cache[idx][f]=ans
    return ans
def solve():
    
    # for _ in range(ii()):
    
    a=[]
    n=ii()
    for i in range(n):
        a.append(li())
    cache=[[-1,-1,-1] for i in range(n)]
    print(max(dp(0,0,a,cache),dp(0,1,a,cache),dp(0,2,a,cache)))
    
   
    
    
    
    
    
    
    
    
    
    
    
    
    
    
        
        
        
        
if __name__ =="__main__":
    solve()

Submission status: Runtime Error

Solution code:
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College
    Date:11/06/2020

'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

def dp(idx,f):
    if idx==n:
        return 0
    if cache[idx][f]!=-1:
        return cache[idx][f]
    ans=0
    for i in range(3):
        if i==f:
            continue
        ans=max(ans,dp(idx+1,i))
    ans+=a[idx][f]
    cache[idx][f]=ans
    return ans
def solve():
    
    # for _ in range(ii()):
    global a
    a=[]
    global n
    n=ii()
    for i in range(n):
        a.append(li())
    global cache
    cache=[[-1,-1,-1] for i in range(n)]
    print(max(dp(0,0),dp(0,1),dp(0,2)))
    
   
    
    
    
    
    
    
    
    
    
    
    
    
    
    
        
        
        
        
if __name__ =="__main__":
    solve()

Submission status: Runtime Error

Solution code:
# key not available ""
n = int(input())
matrix = []
for _ in range(n):
    matrix.append([int(i) for i in input().split()])
dp = [[0 for i in range(10)] for j in range(n+1)]


def go(i, j):
    if i < 0:
        return 0
    ans = 0
    if dp[i][j] > 0:
        return dp[i][j]
    dp[i][j] = max(ans, go(i-1, (j+1) % 3)+matrix[i][j], go(i-1, (j+2) % 3)+matrix[i][j])
    return dp[i][j]


print(max(go(n-1, 2),go(n-1,1),go(n-1,0)))

Submission status: Runtime Error

Solution code:
# key not available ""
n = int(input())
matrix = []
for _ in range(n):
    matrix.append([int(i) for i in input().split()])
dp = [[0 for i in range(3)] for j in range(n+1)]


def go(i, j):
    if i < 0:
        return 0
    ans = 0
    if dp[i][j] > 0:
        return dp[i][j]
    dp[i][j] = max(ans, go(i-1, (j+1) % 3)+matrix[i][j], go(i-1, (j+2) % 3)+matrix[i][j])
    return dp[i][j]


print(max(go(n-1, 2),go(n-1,1),go(n-1,0)))

Submission status: Runtime Error

Solution code:
n = int(input())
last_chosen = -1

max_points = 0
for i in range(n):
    days = list(map(int, input().split()))
    while True:
        act = max(days)
        idx = days.index(act)
        if idx != last_chosen:
            break
        days.pop(idx)
    max_points += days[idx]
    last_chosen = idx
print(max_points)

Submission status: Runtime Error

Solution code:
import sys
def maxcost(li,n,i,strt,dp):
    if i==(n-1):
        return li[i][strt]
    mx=-sys.maxsize
    for l in range(3):
        if l!=strt:
            if dp[i+1][l]==-1:
                cost=maxcost(li,n,i+1,l,dp)
                dp[i+1][l]=cost
            else:
                cost=dp[i+1][l]
            mx=max(mx,cost+li[i][strt])
    return mx


n=int(input())
li=[]
for i in range(n):
    temp=[int(x) for x in input().split()]
    li.append(temp)
dp=[[-1 for j in range(3)] for i in range(n)]
print(max(maxcost(li,n,0,0,dp),maxcost(li,n,0,1,dp),maxcost(li,n,0,2,dp)))

Submission status: Runtime Error

Solution code:
from sys import stdin, gettrace
import sys
 
if not gettrace():
    def input():
        return next(stdin)[:-1]
 
 
# def input():
#    return stdin.buffer.readline()

def maxcost(li,n,i,strt,dp):  
  if i==(n-1):
    return li[i][strt]
  mx=-sys.maxsize
  for l in range(3):
    if l!=strt:
      if dp[i+1][l]==-1:
        cost=maxcost(li,n,i+1,l,dp)
        dp[i+1][l]=cost
      else:
        cost=dp[i+1][l]
      mx=max(mx,cost+li[i][strt])
  return mx

def main():
  n=int(input())
  li=[]
  for i in range(n):
    temp=[int(x) for x in input().split()]
  li.append(temp)
  dp=[[-1 for j in range(3)] for i in range(n)]
  print(max(maxcost(li,n,0,0,dp),maxcost(li,n,0,1,dp),maxcost(li,n,0,2,dp)))
 
 
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
class Solution:
	def __init__(self):
		pass
	def solve(self,arr):
		dp=[0]*len(arr)
		dp[0]=arr[0].index(max(arr[0]))
		for i in range(1,len(arr)):
			arr[i][dp[i-1]]=0
			dp[i]=arr[i].index(max(arr[i]))
		res=0
		for i in range(len(arr)):
			res+=arr[i][dp[i]]
		return(res)
obj=Solution()
#print(obj.solve([[6,7,8],[8,8,3],[2,5,2],[7,8,6],[4,6,8],[2,3,4],[7,5,1]]))
n=int(input().strip())
activities=[[] for _ in range(n)]
for i in range(n):
	activities[i]=list(map(int,input().strip()))
print(obj.solve(activities))

Submission status: Runtime Error

Solution code:
class Solution:
	def __init__(self):
		pass
	def solve(self,arr):
		dp=[0]*len(arr)
		dp[0]=arr[0].index(max(arr[0]))
		for i in range(1,len(arr)):
			arr[i][dp[i-1]]=0
			dp[i]=arr[i].index(max(arr[i]))
		res=0
		for i in range(len(arr)):
			res+=arr[i][dp[i]]
		return(res)
obj=Solution()
#print(obj.solve([[6,7,8],[8,8,3],[2,5,2],[7,8,6],[4,6,8],[2,3,4],[7,5,1]]))
n=int(input().strip())
activities=[[] for _ in range(n)]
for i in range(n):
	activities[i]=[int(input().strip()),int(input().strip()),int(input().strip())]
print(obj.solve(activities))

Submission status: Runtime Error

Solution code:
N, W = map(int, input().split(" "))
items = [tuple(map(int, input().split(" "))) for _ in range(N)]
dp = [[0]*(W+1) for i in range(N+1)]

for i in range(1, N+1):
    w, v = items[i-1]
    for j in range(1, W+1):
        if j >= w:
            dp[i][j] = max(dp[i-1][j], dp[i-1][j-w]+v)
        else:
            dp[i][j] = dp[i-1][j]

print(dp[N][W])

Submission status: Runtime Error

Solution code:
N = int(input())
ABC = np.array([list(map(int,input().split())) for _ in range(N)])


dp = [[0, 0, 0] for _ in range(N)]
dp[0] = ABC[0]

select_action = [[1,2], [0,2], [0,1]]
for i in range(1,N):
    for j in range(3):
        abc1 = select_action[j][0]
        abc2 = select_action[j][1]

        dp[i][j] = max(dp[i-1][abc1], dp[i-1][abc2]) + ABC[i][j]


print(max(dp[-1]))

Submission status: Runtime Error

Solution code:
import numpy as np

N = int(input())
ABC = np.array([list(map(int,input().split())) for _ in range(N)])


dp = [[0, 0, 0] for _ in range(N)]
dp[0] = ABC[0]

select_action = [[1,2], [0,2], [0,1]]
for i in range(1,N):
    for j in range(3):
        abc1 = select_action[j][0]
        abc2 = select_action[j][1]

        dp[i][j] = max(dp[i-1][abc1], dp[i-1][abc2]) + ABC[i][j]


print(max(dp[-1]))

Submission status: Runtime Error

Solution code:
def maxim(i,char):
    if i<0:
        return 0

    if char=='C':
        return max(c[i]+maxim(i-1,'B'),c[i]+maxim(i-1,'A'))
    if char=='B':
        return max(b[i] + maxim(i - 1, 'A'), b[i] + maxim(i - 1, 'C'))
    if char=='A':
        return max(a[i] + maxim(i - 1, 'B'), a[i] + maxim(i - 1, 'C'))
n=int(input())
a, b, c = [], [], []
for _ in range(n):
    ##a,b,c=[],[],[]
    x,y,z=map(int,input().split())
    a.append(x)
    b.append(y)
    c.append(z)
##print(a,b,c)
print(max(maxim(n-1,'C'),maxim(n-1,'B'),maxim(n-1,'A')))

Submission status: Runtime Error

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
def main():
    N, W = map(int, readline().split())
    INF = int(1e5)+100
    weight = [0 for _ in range(110)]
    value = [0 for _ in range(110)] 
    for i in range(N):
        w, v = map(int, readline().split())
        weight[i] = w
        value[i] = v
    dp = [[0 for _ in range(INF)] for _ in range(110)]
    for i in range(N):
        for sum_w in range(W+1):
            if sum_w - weight[i] >= 0:
                dp[i+1][sum_w] = max(dp[i+1][sum_w], dp[i][sum_w-weight[i]] + value[i]) 
            dp[i+1][sum_w] = max(dp[i+1][sum_w], dp[i][sum_w])
    print(dp[N][W])
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys,io
from functools import lru_cache
sys.setrecursion(10**6)
#read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def read():
  return int(readline())
def reads():
  return map(int, readline().split())
def mp(arg):
  return map(int,arg.split())
n=read()
a,b,c=[0]*n,[0]*n,[0]*n
for i,line in enumerate(readlines()):
    a[i],b[i],c[i]=mp(line)
dp=[]
@lru_cache(None)
def dp(k,choice):
    if k==0:
        return 0
    one=dp(k-1,1)+a[k-1]
    two=dp(k-1,2)+b[k-1]
    zero=dp(k-1,0)+c[k-1]
    if choice==0:
        return one if one >= two else two
    if choice==1:
        return zero if zero >= two else two
    if choice==2:
        return one if one >= zero else zero
print(max(dp(n,0),dp(n,1),dp(n,2)))

Submission status: Runtime Error

Solution code:
from sys import stdin,stdout
inp = stdin.readline
out = stdout.write
n = int(inp())
dp = [[0 for _ in range(3)] for _ in range(n)]
dp[0] = map(int,inp().split())
for i in range(1,n):
    a,b,c = map(int,inp().split())
    dp[i][0] = max(dp[i][1]+b[i],dp[i][2]+c[i])
    dp[i][1] = max(dp[i][0]+a[i],dp[i][2]+c[i])
    dp[i][2] = max(dp[i][1]+b[i],dp[i][0]+a[i])
out(str(max(dp[n-1])))

Submission status: Runtime Error

Solution code:
n,v=[int(k) for k in input().split()]
li=[]
for i in range(n):
  li.append([int(k) for k in input().split()])
  
dp=[[0 for i in range(v+1)] for j in range(n+1)]
for a in range(1,n+1):
  for b in range(1,v+1):
    if(li[a-1][0]<=b):
      dp[a][b]=max(li[a-1][1]+dp[a-1][b-li[a-1][0]],dp[a-1][b])
    else:
      dp[a][b]=dp[a-1][b]
print(dp[n][v])

Submission status: Runtime Error

Solution code:
import numpy as np
n = int(input())
H = np.array([list(map(int, input().split())) for _ in range(n)], dtype = np.int)
dp = np.zeros((n, 3), dtype = np.int)
dp[0] = H[0]
def except_ind(num):
    ind = np.ones((3, ), dtype = bool)
    ind[num] = False
    return ind
for i in range(1, n):
    for j in range(3):
        dp[i][j] = np.max(dp[i - 1][except_ind(j)]) + H[i][j]
print(np.max(dp[n - 1]))

Submission status: Runtime Error

Solution code:
#-*-coding:utf-8-*-

import sys
import numpy as np

def choose_activity(idx,data,tmp):
    del data[idx]
    activity=max(data)
    idx=data.index(max(data))
    tmp.append(idx)
    return idx,activity

def main():
    n = int(input())
    datas=list([[int(i) for i in input().split()] for _ in range(n)])
    tmp=[]
    activity=[]

    for idx,data in enumerate(datas):
        if len(activity)==0:
            activity.append(max(data))
            tmp.append(data.index(max(data)))
        else:
            idx,data=choose_activity(tmp[idx-1],data,tmp)
            activity.append(data)
            tmp.append(data)
    print(sum(activity))

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
def resolve():
    import sys
    input = sys.stdin.readline
    # 整数 1 つ
    n = int(input())
    # 整数複数個
    # a, b = map(int, input().split())
    # 整数 N 個 (改行区切り)
    # N = [int(input()) for i in range(N)]
    # 整数 N 個 (スペース区切り)
    # N = list(map(int, input().split()))
    # 整数 (縦 H 横 W の行列)
    A = [list(map(int, input().split())) for i in range(n)]

    Happy = [0, 0, 0] * (n+1)
    for i in range(1, n+1):
        for j in range(3):
            for k in range(3):
                if j != k:
                    Happy[i][j] = max(Happy[i][j], Happy[i-1][k] + A[i-1][j])

    print("n")


resolve()

Submission status: Runtime Error

Solution code:
n=int(input())
a=[]
for _ in range(n):
    a.append(list(map(int,input().split())))
dp=[0]*n
for i in range(3):
  dp[i]=a[0][i]
for k in range(1,n):
    m=[0]*3
    for i in range(3):
        for j in range(3):
            if i!=j:
                m[i]=max(m[i],dp[j]+a[k][i])
    dp=m
print(max(m))

Submission status: Runtime Error

Solution code:
n=int(input())
a=[]
for _ in range(n):
    a.append(list(map(int,input().split()))) 
dp=[0]*n
for i in range(3):
  dp[i]=a[0][i]
for k in range(1,n):
    m=[0,0,0]
    for i in range(3):
        for j in range(3):
            if i!=j:
                m[i]=max(m[i],dp[j]+a[k][i])
    dp=m
print(max(m))

Submission status: Runtime Error

Solution code:
n=int(input())
a=[]
for _ in range(n):
    a.append(list(map(int,input().split())))
dp=a[0]

for k in range(1,n):
    m=[0,0,0]
    for i in range(3):
        for j in range(3):
            if i!=j:
                m[i]=max(m[i],dp[j]+a[k][i])
    dp=m
print(max(m))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(int(1e6))

n=int(input())
l=[[0,0,0]]
for _ in range(n):
    l.append(list(map(int,input().split())))

memo=[[-1,-1,-1] for _ in range(n+1)]
memo[0][0]=0
memo[0][1]=0
memo[0][2]=0
def dp(i,j):
    z[i][j]=1
    if memo[i][j]!=-1:
        return memo[i][j]
    else:
        memo[i][j]=max(dp(i-1,(j+1)%3)+l[i][j],dp(i-1,(j+2)%3)+l[i][j])
        return memo[i][j]
s1=dp(n,0)
s2=dp(n,1)
s3=dp(n,2)
print(max(s1,s2,s3))

Submission status: Runtime Error

Solution code:
n=int(input())
l=[[0,0,0]]
for _ in range(n):
    l.append(list(map(int,input().split())))

memo=[[-1,-1,-1] for _ in range(n+1)]
memo[0][0]=0
memo[0][1]=0
memo[0][2]=0
def dp(i,j):
    if memo[i][j]!=-1:
        return memo[i][j]
    else:
        memo[i][j]=max(dp(i-1,(j+1)%3)+l[i][j],dp(i-1,(j+2)%3)+l[i][j])
        return memo[i][j]
print(max(dp(n,0),dp(n,1),dp(n,2)))

Submission status: Runtime Error

Solution code:

def resolve():
    n = int(input())
    action = []
    for i in range(n):
        action.append([int(i) for i in input().split()])
    df = []
    df.append(max(action[0]))
    prev = action[0].index(max(action[0]))
    for i in range(1, n):
        tgt = max([action[i][j] for j in range(len(action[i])) if j != prev])
        prev = action[i].index(tgt)
        df.append(tgt)
    print(sum(df))

if __name__ = "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
N = input()

max_a= [0]*N
max_b = [0]*N
max_c = [0]*N

for i in range(0,N):
  a,b,c = map(int,input.split())
  max_a[i] = max(max_b[i-1]+a,max_c+a) 
  max_b[i] = max(max_a[i-1]+b,max_c[i-1]+b) 
  max_c[i] = max(max_a[i-1]+c,max_b[i-1]+c) 
  
print(max(max_a[-1],max_b[-1],max_c[-1]))

Submission status: Runtime Error

Solution code:
## necessary imports
#import sys
#input = sys.stdin.readline
from math import log2, log, ceil

# swap_array function
def swaparr(arr, a,b):
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp

## gcd function
def gcd(a,b):
    if a == 0:
        return b
    return gcd(b%a, a)

## nCr function efficient using Binomial Cofficient
def nCr(n, k): 
    if(k > n - k): 
        k = n - k 
    res = 1
    for i in range(k): 
        res = res * (n - i) 
        res = res / (i + 1) 
    return res 

## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0):
    hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] < x:
            lo = mid+1
        else:
            hi = mid
    return lo

## prime factorization
def primefs(n):
    ## if n == 1    ## calculating primes
    primes = {}
    while(n%2 == 0):
        primes[2] = primes.get(2, 0) + 1
        n = n//2
    for i in range(3, int(n**0.5)+2, 2):
        while(n%i == 0):
            primes[i] = primes.get(i, 0) + 1
            n = n//i
    if n > 2:
        primes[n] = primes.get(n, 0) + 1
    ## prime factoriazation of n is stored in dictionary
    ## primes and can be accesed. O(sqrt n)
    return primes

## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p): 
    res = 1
    x = x % p  
    if (x == 0) : 
        return 0
    while (y > 0) : 
        if ((y & 1) == 1) : 
            res = (res * x) % p 
        y = y >> 1      
        x = (x * x) % p 
    return res 

## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
    temp = a
    a = b
    b = temp
    return a,b

# find function with path compression included (recursive)
# def find(x, link):
#     if link[x] == x:
#         return x
#     link[x] = find(link[x], link);
#     return link[x];

# find function with path compression (ITERATIVE)
def find(x, link):
    p = x;
    while( p != link[p]):
        p = link[p];
    
    while( x != p):
        nex = link[x];
        link[x] = p;
        x = nex;
    return p;


# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
    x = find(x, link)
    y = find(y, link)
    if size[x] < size[y]:
        x,y = swap(x,y)
    if x != y:
        size[x] += size[y]
        link[y] = x

## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n): 
    prime = [True for i in range(n+1)] 
    p = 2
    while (p * p <= n): 
        if (prime[p] == True): 
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    return prime

#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
    spf[1] = 1;
    for i in range(2, MAXN):
        spf[i] = i;
    for i in range(4, MAXN, 2):
        spf[i] = 2;
    for i in range(3, ceil(MAXN ** 0.5), 2):
        if spf[i] == i:
            for j in range(i*i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i;
    ## function for storing smallest prime factors (spf) in the array

################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve() 
def factoriazation(x):
    ret = {};
    while x != 1:
        ret[spf[x]] = ret.get(spf[x], 0) + 1;
        x = x//spf[x]
    return ret
    ## this function is useful for multiple queries only, o/w use
    ## primefs function above. complexity O(log n)

## taking integer array input
def int_array():
    return list(map(int, input().strip().split()))
## taking string array input
def str_array():
    return input().strip().split();

#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');

################### ---------------- TEMPLATE ENDS HERE ---------------- ###################

n = int(input());
xx,yy,zz = 0,0,0;
for _ in range(n):
    a,b,c = int_array();
    x = a + max(yy, zz);
    y = b + max(xx, zz);
    z = c + max(xx, yy);
    xx, yy, zz = x, y, z;
print(max(xx, yy, zz));

Submission status: Runtime Error

Solution code:
n=int(input())
import copy
l=[list(map(int,input().split())) for i in range(n)]
q=copy.copy(l)
dp=[0]*(n+1)
dp[0]=0
dp[1]=max(l[0])
for i in range(1,n-1):
  if l[i+1].index(max(l[i+1]))==l[i].index(max(l[i]):
    qq=q[i+1].sort()                                      
    dp[i+1]=max(dp[i-1]+max(l[i+1]),dp[i]+qq[1])
print(n)

Submission status: Runtime Error

Solution code:
n = int(input())
k=-1
tot=0
for i in range(n):
    m=list(map(int,input().split()))
    max_val = max(m)
    ind = m.index(max_val)
    
    if(ind!=k):
        tot+=m[ind]
        k=ind
    else:
        p=sorted(set(m))
        b=p[1]
        c=m.index(b)
        tot+=b
        k=c
print(tot)

Submission status: Runtime Error

Solution code:
# import sys
# sys.setrecursionlimit(10**5)
# from collections import defaultdict
geta = lambda fn: list(map(fn, input().split()))
gete = lambda fn: fn(input())

N = gete(int)

cur = [0] * 3

for _ in range(N):
    a, b, c = geta(int)
    prev = cur.copy()
    cur[0] = max(prev[1], prev[2]) + a
    cur[1] = max(prev[2], prev[0]) + b
    cur[2] = max(prev[0], prev[1]) + c

print(max(cur))

Submission status: Runtime Error

Solution code:
def solve(n,pos):
    global data,helper
    if(n==-1):
        return 0
    if(helper[n][pos]!=-1):
        return helper[n][pos]
    if(pos==0):
        helper[n][pos]=max(data[n][1]+solve(n-1,1),data[n][2]+solve(n-1,2))
        return helper[n][pos]
    elif(pos==1):
        helper[n][pos] = max(data[n][0]+solve(n-1,0),data[n][2]+solve(n-1,2))
        return helper[n][pos]
    else:
        helper[n][pos] = max(data[n][1]+solve(n-1,1),data[n][0]+solve(n-1,0))
        return helper[n][pos]
n=int(input())
data=[]
helper=[[-1 for y in range(3)] for x in range(n)]
for _ in range(n):
    temp=[int(x) for x in input().split()]
    data.append(temp)
t1=data[-1][0]+solve(n-2,0)
t2=data[-1][1]+solve(n-2,1)
t3=data[-1][2]+solve(n-2,2)
print(max(t1,t2,t3))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(100000)
x=int(input())
A=[]
B=[]
C=[]
dictA=[-1]*x
dictB=[-1]*x
dictC=[-1]*x
for i in range(x):
    a,b,c=list(map(int,input().split()))
    A.append(a)
    B.append(b)
    C.append(c)
def maxA(n):
    if dictA[n]!=-1:
        return dictA[n]
    if n==0:
        dictA[n]=A[0]
        return A[0]
    dictA[n]=A[n]+max(maxB(n-1),maxC(n-1))
    return dictA[n]
def maxB(n):
    if dictB[n]!=-1:
        return dictB[n]
    if n==0:
        dictB[n]=B[0]
        return B[0]
    dictB[n]=B[n]+max(maxA(n-1),maxC(n-1))
    return dictB[n]
def maxC(n):
    if dictC[n]!=-1:
        return dictC[n]
    if n==0:
        dictC[n]=C[0]
        return C[0]
    dictC[n]=C[n]+max(maxB(n-1),maxA(n-1))
    return dictC[n]
def Nmax(n):
    return max(maxA(n),maxB(n),maxC(n))
print(Nmax(x-1))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(100000)
x=int(input())
A=[]
B=[]
C=[]
dictA=[-1]*x
dictB=[-1]*x
dictC=[-1]*x
for i in range(x):
    a,b,c=list(map(int,input().split()))
    A.append(a)
    B.append(b)
    C.append(c)
def maxA(n):
    if dictA[n]!=-1:
        return dictA[n]
    if n==0:
        dictA[n]=A[0]
        return A[0]
    dictA[n]=A[n]+max(maxB(n-1),maxC(n-1))
    return dictA[n]
def maxB(n):
    if dictB[n]!=-1:
        return dictB[n]
    if n==0:
        dictB[n]=B[0]
        return B[0]
    dictB[n]=B[n]+max(maxA(n-1),maxC(n-1))
    return dictB[n]
def maxC(n):
    if dictC[n]!=-1:
        return dictC[n]
    if n==0:
        dictC[n]=C[0]
        return C[0]
    dictC[n]=C[n]+max(maxB(n-1),maxA(n-1))
    return dictC[n]
def Nmax(n):
    return max(maxA(n),maxB(n),maxC(n))
print(Nmax(x-1)%10000)

Submission status: Runtime Error

Solution code:
x=int(input())
A=[]
B=[]
C=[]
for i in range(x):
    a,b,c=list(map(int,input().split()))
    A.append(a)
    B.append(b)
    C.append(c)
def maxA(n):
    if n==0:
        return A[0]
    return A[n]+max(maxB(n-1),maxC(n-1))
def maxB(n):
    if n==0:
        return B[0]
    return B[n]+max(maxC(n-1),maxA(n-1))
def maxC(n):
    if n==0:
        return C[0]
    return C[n]+max(maxA(n-1),maxB(n-1))
def Nmax(n):
    return max(maxA(n),maxB(n),maxC(n))
print(Nmax(x-1))

Submission status: Runtime Error

Solution code:
def calculate(m,n):
  dp=[[0 for j in range(n)] for i in range(n)]
  best=0
  for i in range(n):
    for j in range(n):
        if i!=j:
            dp[i][j]=max(dp[i][j],dp[i][j]+m[i][j]) 
    best+=max(dp[i])
  return best
 
def main():
    n=int(input())
    m=[[n]]*(n)
    for i in range(n):
        m[i]=list(map(int,input().split())) 
    print(calculate(m,n))
 
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#With the intution that Which day I should have chosen previously to get max happiness

n = int(input())
happMatrix = []
for i in range(n):
    dayi = list(map(int,input().split()))
    happMatrix.append(dayi)

dp = happMatrix[0]
prevDayHelperMatrix = [0]*3
# print(dp,prevDayHelperMatrix,"--")
for i in range(1,n):
    prevDayHelperMatrix[0] = max(dp[1],dp[2])+happMatrix[i][0]
    prevDayHelperMatrix[1] = max(dp[0],dp[2])+happMatrix[i][1]
    prevDayHelperMatrix[2] = max(dp[0],dp[1])+happMatrix[i][2]
    # print(dp,prevDayHelperMatrix,"-+")
    dp = prevDayHelperMatrix.copy()
# print(dp,prevDayHelperMatrix,"--++")
print(max(dp))

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.readline
def main():
    n=int(input())
    #H=[list(map(int,input().split())) for _ in range(n)]
    dp=[[-10**9]*3 for _ in range(n)]
    
    for i in range(n):
        a,b,c=map(int,input().split())
        t=[a,b,c]
        if i==0:
            dp[0][0],dp[0][1],dp[0][2]=a,b,c 
        else:
            for j in range(3):
                dp[i][j]=max(dp[i-1][j-1]+t[j-1],dp[i-2]+t[j-2])

        print(max(dp[-1]))
main()

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
h=list(map(int,input().split()))
dp=[float('inf')]*(N+1)
dp[0]=0
for i in range(N-1):
    for j in range(1,K+1):
        if i+j>N-1:
            break
        else:
            dp[i+j]=min(dp[i+j],dp[i]+abs(h[i]-h[i+j]))
print(dp[N-1])

Submission status: Runtime Error

Solution code:
N = int(input())
dpa = [0] * N
dpb = dpa.copy()
dpc = dpa.copy()

a, b, c = map(int, input().split())
dpa[0] = a
dpb[0] = b
dpc[0] = c
for i in range(1, N):
    a, b, c = map(int, input().split())
    dpa[i] = max(dpb[i-1] + a, dpc[i-1] + a)
    dpb[i] = max(dpa[i-1] + b, dpc[i-1] + b)
    dpc[i] = max(dpa[i-1] + c, dpb[i-1] + c)

print(max(dpa[N-1], dpb[N-1], dpc[N-1]))

Submission status: Runtime Error

Solution code:
N = int(input())
abc = [list(map(int, input().split())) for _ in range(3)]

dp = [[0] * 3 for _ in range(N+1)]

for i in range(1, N+1):
    for j in range(3):
        for k in range(3):
            if j != k:
                dp[i][j] = max(dp[i][j], dp[i-1][k] + abc[i-1][k])

print(max(dp[N]))

Submission status: Runtime Error

Solution code:
n = int(input())

abc=list()
for i in range(n):
    abc.append([int(e) for e in input().split()])

A=[]
B=[]
C=[]

for i in range(n):
    a = abc[i][0] + max(B[-1],C[-1])
    b = abc[i][1] + max(A[-1],C[-1])
    c = abc[i][2] + max(A[-1],B[-1])
    A.append(a)
    B.append(b)
    C.append(c)

print(max(A[-1],B[-1],C[-1]))

Submission status: Runtime Error

Solution code:
N = int(input())
happiness_matrix = []
for _ in range(N):
    row = input()
    happiness_matrix.append(list(map(int, row.split(' '))))

def solve_vacation(N, happiness_matrix):
    # Each of the following arrays:
    # maximum possible happiness BUT we end the day by taking that action
    # Day 0 -- just choose the best activity
    last_swim = happiness_matrix[0][0]
    last_bug = happiness_matrix[0][1]
    last_homework = happiness_matrix[0][2]

    for i in range(1, N):
        swim, bug, homework = happiness_matrix[i]

        option1 = last_bug + swim
        option2 = last_homework + swim
        best_swim = max(option1, option2)

        option3 = last_swim + bug
        option4 = last_homework + bug
        best_bug = max(option3, option4)

        option5 = last_swim + homework
        option6 = last_bug + homework
        best_homework = max(option5, option6)

        last_swim, last_bug, last_homework = best_swim, best_bug, best_homework

    return max(best_swim, best_bug, best_homework)

print(solve_vacation(N, happiness_matrix))

Submission status: Runtime Error

Solution code:
n = int(input())

happiness_matrix = []
for _ in range(n):
  row = input()
  happiness_matrix.append(list(map(int, row.split(' ')))

def solve_vacation(N, happiness_matrix):
    # Each of the following arrays:
    # maximum possible happiness BUT we end the day by taking that action
    # Day 0 -- just choose the best activity
    last_swim = happiness_matrix[0][0]
    last_bug = happiness_matrix[0][1]
    last_homework = happiness_matrix[0][2]

    for i in range(1, N):
        swim, bug, homework = happiness_matrix[i]

        option1 = last_bug + swim # don't swim
        option2 = last_homework + swim # do swim
        best_swim = max(option1, option2)

        option3 = last_swim + bug
        option4 = last_homework + bug
        best_bug = max(option3, option4)

        option5 = last_swim + homework
        option6 = last_bug + homework
        best_homework = max(option5, option6)

        last_swim, last_bug, last_homework = best_swim, best_bug, best_homework

    return max(best_swim, best_bug, best_homework)

print(solve_vacation(n, happiness_matrix))

Submission status: Runtime Error

Solution code:
def pathSmMax(matrix,i,j,cache):
    if i > len(matrix)-1: return 0
    happiness = 0
    if cache[i][j] != 0:
        return cache[i][j]
    for k in range(3):
        if k != j:
            cache[i][j] = max(cache[i][j],pathSmMax(matrix,i+1,k,cache) + matrix[i][j])
    return cache[i][j]
N = int(input())
matrix = []
for i in range(N):
    matrix.append([int(i) for i in input().split()])
maxs = -float("inf")
cache = [[0 for i in range(4)] for j in range(len(matrix)+1)]
for i in range(len(matrix)):
    maxs = max(maxs,pathSmMax(matrix,0,i,cache))
print(maxs)