Skip to content

Commit

Permalink
Kadane problem
Browse files Browse the repository at this point in the history
  • Loading branch information
harrypotter0 committed Jan 21, 2018
1 parent 2024e14 commit fc41ada
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 28 deletions.
70 changes: 42 additions & 28 deletions CP/January Challenge 2018/kconcat.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,43 @@
'''
listB.sort(reverse=True) # listB gets modified
listC = sorted(listB, reverse=True) # listB remains untouched
'''


for _ in range(int(input())):
n = int(input())
b = []
for __ in range(n):
a = map(int,raw_input().split())
b.append(sorted(a))
su = b[n-1][-1]
k1=su

for x in range(n-2,-1,-1):
flag = 0
for y in range(n-1,-1,-1):
if(b[x][y]<k1):
k1=b[x][y]
su+=k1
flag = 1
break
if(flag == 0):
break
if(flag == 0):
print("-1")
int_min = -float('inf')

def kadane(a , k):
n = len(a)
temp = 0
maxm = int_min
while k :
k -= 1

for i in range(n):
temp += a[i]
if temp > maxm :
maxm = temp

if temp < 0 :
temp = 0

return maxm

t = int(raw_input())
for a0 in range(t):
n,k = map(int , raw_input().split())
arr = map(int , raw_input().split())

sumi = 0
maxi = -float('inf')

s1 = kadane(arr , 1)
s2 = kadane(arr , 2)
s3 = kadane(arr , 3)
s4 = kadane(arr , 4)

if s1 == s2 :
print s1
else :
print(su)
if k == 1 :
print s1
elif k == 2:
print s2
elif k == 3 :
print s3
else :
print s3 + (k-3)*(s4-s3)
33 changes: 33 additions & 0 deletions CP/January Challenge 2018/kconcat1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
int_min = -float('inf')
def maxSubArraySum(a,k):
max_so_far = int_min
max_ending_here = 0
while k:
k-=1
for i in range(0, len(a)):
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here

if max_ending_here < 0:
max_ending_here = 0

return max_so_far

# Driver function to check the above function
#print "Maximum contiguous sum is", maxSubArraySum(a,len(a))

for __ in range(int(input())):
n,k = map(int,raw_input().split())
a = map(int,raw_input().split())
s1 = maxSubArraySum(a , 1)
s2 = maxSubArraySum(a , 2)
s3 = maxSubArraySum(a , 3)
s4 = maxSubArraySum(a , 4)

if k == 1 :
print s1
elif k == 2:
print s2
else :
print s2 + (k-2)*(s3-s2)

0 comments on commit fc41ada

Please sign in to comment.