Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # cook your dish here
- # https://www.codechef.com/problems/PREPER?tab=statement
- def check(sum,i):
- return sum == ((i*(i+1))//2)# a permutation pref is good if its sum is matching with sum of N natural numbers that means all numbers are present none are missing
- def maxSubArrSum(p):
- maxi = float('-inf')
- currMax = 0
- for ele in p:
- currMax += ele
- if currMax > maxi:
- maxi = currMax
- if currMax < 0:
- currMax = 0#resetting
- return maxi
- def getMaxGoodPrefs(arr):
- #let g be the current good prefixes
- g = 0
- sum = 0
- for i in range(len(arr)):
- sum += arr[i]
- if check(sum,i+1):
- g += 1
- '''
- now you have 2 ways to swap
- important thing is no matter what L and R you choose
- only adjacent elements will be swapped
- which is odd even swapping
- and even odd swapping
- we need to perform 2 ways and check the max possible
- and also our aim is to enhance g not to ruin it
- '''
- #include first element and check 2 steps
- #if they swapped and not swapped
- sumf = 0
- poe = []
- n = len(arr)
- for i in range(0,n,2):
- gnotswap = 0
- gswap = 0
- if i+1<n:
- #if not swap
- if check(sumf+arr[i],i+1):
- gnotswap += 1
- #for next position arr[i] needs to be included
- sumf += arr[i]
- if check(sumf+arr[i+1],i+2):
- gnotswap += 1
- sumf -= arr[i] #nullifying after check
- #if swapped that means arr[i+1] is the first element in this pair
- if check(sumf+arr[i+1],i+1):
- gswap += 1
- #for next position arr[i+1] needs to be included
- sumf += arr[i+1]
- if check(sumf+arr[i],i+2):
- gswap += 1
- sumf -= arr[i+1] #nullifying after check
- sumf += arr[i] + arr[i+1]#preparing for next pair
- diff = gswap-gnotswap
- poe.append(diff)
- sumse = arr[0] #as we are not touching for changing
- peo = []
- for i in range(1,n,2):
- gnotswap = 0
- gswap = 0
- if i+1<n:
- #if not swap
- if check(sumse+arr[i],i+1):
- gnotswap += 1
- #for next position arr[i] needs to be included
- sumse += arr[i]
- if check(sumse+arr[i+1],i+2):
- gnotswap += 1
- sumse -= arr[i] #nullifying after check
- #if swapped that means arr[i+1] is the first element in this pair
- if check(sumse+arr[i+1],i+1):
- gswap += 1
- #for next position arr[i+1] needs to be included
- sumse += arr[i+1]
- if check(sumse+arr[i],i+2):
- gswap += 1
- sumse -= arr[i+1] #nullifying after check
- sumse += arr[i] + arr[i+1]#preparing for next pair
- diff = gswap-gnotswap
- peo.append(diff)
- max1 = maxSubArrSum(poe)
- max2 = maxSubArrSum(peo)
- maxChangedG = max(0,max1,max2)
- return g+maxChangedG
- def main():
- tc = int(input())
- for i in range(tc):
- n = int(input())
- arr = list(map(int,input().split()))
- curr = getMaxGoodPrefs(arr)
- print(curr)
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement