Easy algorithm-Leet code- Maximum sub array - python

Struggling to wrap my head around this.
Maximum Subarray
Easy
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
subarray1=[]
subarray2=[]
for n in nums:
subarray1.append(sum(nums[nums.index(n):]))
nums2=nums[::-1]
subarray2.append(sum(nums2[nums.index(n):]))
para1=subarray1.index(max(subarray1))
para2=len(nums)-subarray2.index(max(subarray2))
ans=sum(nums[para1:para2])
if sum(nums)>ans :
ans=sum(nums)
if len(nums)==2 and sum(nums)< nums[0] or nums[1] :
ans=max(nums)
return ans
I'm don't understand the iterative logic and the answers from vids are coming up wrong.
My logic is to create an array summing the input array from both sides and use the index of max values on those 2 arrays to figure out the maximum sum sub array parameters.
My answer is supposedly wrong when copied onto leet code https://leetcode.com/problems/maximum-subarray/
Been trying for hours, it's marked as easy. Im sure there is an easy iterative way of doing it but everything I've search is wrong so far.

There is a standard logic to many of these problems. Assume you know what subarray with the largest total is nums[:n - 1]. Then what is the subarray with the largest total you can find for the subarray nums[:n]?
There are two possibilities:
The new answer doesn't contain nums[n-1]. In that case, it has to be the same answer as the old answer
The new answer does contain nums[n-1].
So. . .
The actual algorithm is that you iteratively go through the array, repeatedly adding a new element to the array, and keeping track of two answers:
What is the subarray with the largest total
What is the subarray with the largest total containing the last element.
(This answer may be the same as the previous.)
When you then add a new element to the end of the array:
The subarray with the largest total is either (a) the previous largest total or (b) the previous largest total containing the last element plus the new last element or (c) just the last element. Pick the one with the largest total.
The subarray with the largest total containing the last element is the larger of (b) or (c) above.

class Solution:
def maxSubArray(self, nums: List[int]) -> int:
for i in range(1, len(nums)):
if nums[i-1] > 0:
nums[i] += nums[i-1]
return max(nums)
This is a 2 pass O(n) time complexity solution with constant space.
How it works:
We add each element to its predecessor, provided the predecessor is greater than 0 (greater or equal would also do). The Idea is this: If negative numbers have managed to take it below 0, we discard the prefix and don't care about them anymore. But if some positive value is remaining, we add it since it's better than nothing.
At the end we look for the max value.
To make it one pass, you could just have a best value that at each iteration takes the max. Then you wouldn't need to loop over the array at the end again to take the max.
This is by the way Kadane's algorithm, if you are interested to further read about it.

You can use the Kadane's algorithm to solve this problem in O(n) time and space (and constant extra space). It is a simple dynamic programming algorithm:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum = -10**4
current_sum = 0
for n in nums:
current_sum = n if n > current_sum+n else current_sum+n
if current_sum > max_sum:
max_sum = current_sum
return max_sum

Here's my solution, although it exceeds time limit when the input list has a lot of elements. My idea is to try the sum of every sublist and update the max sum accordingly. There's a faster, but more complex approach by using "divide and conquer" method: https://leetcode.com/problems/maximum-subarray/discuss/1849465/Divide-and-Conquer-Approach-with-Python
My solution (works in 200/209 cases because of Time Limit Exceeded):
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum = - 10 ** 4
for i in range(len(nums)):
for j in range(i + 1, len(nums) + 1):
s = sum(nums[i:j])
if max_sum < s:
max_sum = s
return max_sum

Related

Optimizing performance for max sum in list-of-lists for original list

I am working on my python, doing codewars. The description is as follows:
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:
max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
should be 6: [4, -1, 2, 1]
Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.
Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.
Great! Done! here's my code, which passes the tests:
def max_sequence(arr):
sums = []
lists = [[]]
for i in range(len(arr) + 1):
for j in range(i):
lists.append(arr[j: i])
for i in lists:
sums.append(sum(i))
return max(sums)
However, for submission, codewars requires you to pass a larger battery of tests, and the tests timeout for larger sets.
In the discussion, many people have the same problem as me. One answer in particular gets to the root of the question, which is what i'm asking here (see the comment below):
Your code is not optmised to work with longer arrays, whilst your code likely works, it takes too long to solve the harder problems so times out. This questions is as much an optimisation problem as any. So you need to find a way to optimise your solution
That is very true for me! What am i doing "wrong" in this data structure, and how can i improve it? My current guesses for the most expensive computations are:
loop within loop (for i in range.... for j in range i)
lists.append(arr[j:i])
Any advice? How to improve performance here? I am thinking as much about general data structures and learning as i am about solving this specific question. Thank you!
Similar idea with earlier post, but it tries to bail out earlier when hitting edge cases: (it's still achieved O(n) )
def maxSequence(arr):
if not arr: return 0 # check if it's empty list
if max(arr) < 0: return 0 # check if all negatives
maxx,curr= 0, 0
for x in arr:
curr += x
if curr < 0:
curr = 0
if curr> maxx:
maxx = curr
return maxx
Reference: https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane's_algorithm
You can use Kadane's Algorithm. The idea is that keep adding elements to curr and get the maximum of curr and num. When the sum of the subarray is positive, it keeps going. When the sum of the subarray is negative, it gives up the negative subarray.
You can consider this example with the following code: [-1,1000,-2]. Initially, curr = -1. Since it is negative, curr gives up -1 and gets the value of 1000. Finally, since 1000 is greater than 998, it returns 1000 as the answer.
This only has a time complexity of O(n) instead of the brute force approach that has an O(n^3).
def max_sequence(arr):
if not arr or max(arr) < 0:
return 0
curr = max_sub = arr[0]
for num in arr[1:]:
curr = max(num, curr + num)
max_sub = max(max_sub, curr)
return max_sub

Need help in Python hackerrank problem solving

So, I am stuck on a question and I am not sure what I am doing wrong with my code.
Question is- Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to .
Example a = [1,1,2,2,4,4,5,5,5]
There are two subarrays meeting the criterion: and .
The maximum length subarray has elements.
[1,1,2,2] and [4,4,5,5,5]
Returns
int: the length of the longest subarray that meets the criterion
or visit the link Hackerrank Problem
def pickingNumbers(a):
a.sort()
answer = 0
flag = False
for i in range(len(a)-1,1,-1):
count = 0
temp = [list(l) for l in list(itertools.combinations(a,i))]
for j in temp:
for k in range(len(j)-1):
if abs( j[k+1] - j[k] ) <= 1:
count +=1
if count == len(j):
answer = len(j)
break
Note that the statement asks you to to find a subarray, not subsequence. A subarray is a continuous chain of elements from the parent array. Here by sorting the array you are destroying the parent array's order whenever the array given to you is ascending. Hence your program will give wrong output

Thought process behind the two sums solution (leetcode)? - Python 3

class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = {}
for i, num in enumerate(nums):
n = target - num
if n not in h:
h[num] = i
else:
return [h[n], i]
E.g. nums = [2,7,11,15], target = 9 --> Answer: [0, 1]
Solution is posted above. I know there's plenty of sources of explanations of solutions so far. I understand what each line of the code does and how it is used to arrive at the answer. My dilemma is...how does one conceptualize the answer from scratch? Why does one think to themselves that n = target - num is essential?
yeah, basically my thought process for solving the question may turn out like this
:
(Paraphrasing the question for readers understanding): Return indices of two integers in a given list whose sum is equal to a given target.
i. Like try brute force - which basically mean to add every unique pair of elements in the list, until we get a pair whose sum is equal to the target.
Time Complexity: O(N2) in Worst case. Ex: nums_list = [1,2,3,4] and target = 7
ii. Now, can we reduce the time complexity to O(N)? which means I need to iterate the list only using a single loop, in laymam's terms.
So, iterating only once means, we need to store some values about the visited elements which would help us to find the pair as we iterate the list.
Let us take this small example, given that our target = 10 and our element pair is [A,B], if A = 3, we are for sure that B = 10 - 3 = 7. So, we can check if we have an element B(Difference b/w target and A) in visited elements, if the current element is A, given the target.
So, this given us an idea list keep a track of all visited elements and if the difference between the Target value and the current element is already a visited element, then HOLA!!
We got the pair i.e [Current element, Target - Current element (if available in the visited elements list)]
Just renaming the given code to improve code readability!
class Solution:
def twoSum(self, list_nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
visited_elements = {}
for index, num in enumerate(list_nums):
difference = target - num
if difference not in visited_elements:
visited_elements[num] = index
else:
return [visited_elements[difference], index]
So, that my thought process behind "n = target - num" :)

recursion vs iteration time complexity

Could anyone explain exactly what's happening under the hood to make the recursive approach in the following problem much faster and efficient in terms of time complexity?
The problem: Write a program that would take an array of integers as input and return the largest three numbers sorted in an array, without sorting the original (input) array.
For example:
Input: [22, 5, 3, 1, 8, 2]
Output: [5, 8, 22]
Even though we can simply sort the original array and return the last three elements, that would take at least O(nlog(n)) time as the fastest sorting algorithm would do just that. So the challenge is to perform better and complete the task in O(n) time.
So I was able to come up with a recursive solution:
def findThreeLargestNumbers(array, largest=[]):
if len(largest) == 3:
return largest
max = array[0]
for i in array:
if i > max:
max = i
array.remove(max)
largest.insert(0, max)
return findThreeLargestNumbers(array, largest)
In which I kept finding the largest number, removing it from the original array, appending it to my empty array, and recursively calling the function again until there are three elements in my array.
However, when I looked at the suggested iterative method, I composed this code:
def findThreeLargestNumbers(array):
sortedLargest = [None, None, None]
for num in array:
check(num, sortedLargest)
return sortedLargest
def check(num, sortedLargest):
for i in reversed(range(len(sortedLargest))):
if sortedLargest[i] is None:
sortedLargest[i] = num
return
if num > sortedLargest[i]:
shift(sortedLargest, i, num)
return
def shift(array, idx, element):
if idx == 0:
array[0] = element
return array
array[0] = array[1]
array[idx-1] = array[idx]
array[idx] = element
return array
Both codes passed successfully all the tests and I was convinced that the iterative approach is faster (even though not as clean..). However, I imported the time module and put the codes to the test by providing an array of one million random integers and calculating how long each solution would take to return back the sorted array of the largest three numbers.
The recursive approach was way much faster (about 9 times faster) than the iterative approach!
Why is that? Even though the recursive approach is traversing the huge array three times and, on top of that, every time it removes an element (which takes O(n) time as all other 999 elements would need to be shifted in the memory), whereas the iterative approach is traversing the input array only once and yes making some operations at every iteration but with a very negligible array of size 3 that wouldn't even take time at all!
I really want to be able to judge and pick the most efficient algorithm for any given problem so any explanation would tremendously help.
Advice for optimization.
Avoid function calls. Avoid creating temporary garbage. Avoid extra comparisons. Have logic that looks at elements as little as possible. Walk through how your code works by hand and look at how many steps it takes.
Your recursive code makes only 3 function calls, and as pointed out elsewhere does an average of 1.5 comparisons per call. (1 while looking for the min, 0.5 while figuring out where to remove the element.)
Your iterative code makes lots of comparisons per element, calls excess functions, and makes calls to things like sorted that create/destroy junk.
Now compare with this iterative solution:
def find_largest(array, limit=3):
if len(array) <= limit:
# Special logic not needed.
return sorted(array)
else:
# Initialize the answer to values that will be replaced.
min_val = min(array[0:limit])
answer = [min_val for _ in range(limit)]
# Now scan for smallest.
for i in array:
if answer[0] < i:
# Sift elements down until we find the right spot.
j = 1
while j < limit and answer[j] < i:
answer[j-1] = answer[j]
j = j+1
# Now insert.
answer[j-1] = i
return answer
There are no function calls. It is possible that you can make up to 6 comparisons per element (verify that answer[0] < i, verify that (j=1) < 3, verify that answer[1] < i, verify that (j=2) < 3, verify that answer[2] < i, then find that (j=3) < 3 is not true). You will hit that worst case if array is sorted. But most of the time you only do the first comparison then move to the next element. No muss, no fuss.
How does it benchmark?
Note that if you wanted the smallest 100 elements, then you'd find it worthwhile to use a smarter data structure such as a heap to avoid the bubble sort.
I am not really confortable with python, but I have a different approach to the problem for what it's worth.
As far as I saw, all solutions posted are O(NM) where N is the length of the array and M the length of the largest elements array.
Because of your specific situation whereN >> M you could say it's O(N), but the longest the inputs the more it will be O(NM)
I agree with #zvone that it seems you have more steps in the iterative solution, which sounds like an valid explanation to your different computing speeds.
Back to my proposal, implements binary search O(N*logM) with recursion:
import math
def binarySearch(arr, target, origin = 0):
"""
Recursive binary search
Args:
arr (list): List of numbers to search in
target (int): Number to search with
Returns:
int: index + 1 from inmmediate lower element to target in arr or -1 if already present or lower than the lowest in arr
"""
half = math.floor((len(arr) - 1) / 2);
if target > arr[-1]:
return origin + len(arr)
if len(arr) == 1 or target < arr[0]:
return -1
if arr[half] < target and arr[half+1] > target:
return origin + half + 1
if arr[half] == target or arr[half+1] == target:
return -1
if arr[half] < target:
return binarySearch(arr[half:], target, origin + half)
if arr[half] > target:
return binarySearch(arr[:half + 1], target, origin)
def findLargestNumbers(array, limit = 3, result = []):
"""
Recursive linear search of the largest values in an array
Args:
array (list): Array of numbers to search in
limit (int): Length of array returned. Default: 3
Returns:
list: Array of max values with length as limit
"""
if len(result) == 0:
result = [float('-inf')] * limit
if len(array) < 1:
return result
val = array[-1]
foundIndex = binarySearch(result, val)
if foundIndex != -1:
result.insert(foundIndex, val)
return findLargestNumbers(array[:-1],limit, result[1:])
return findLargestNumbers(array[:-1], limit,result)
It is quite flexible and might be inspiration for a more elaborated answer.
The recursive solution
The recursive function goes through the list 3 times to fins the largest number and removes the largest number from the list 3 times.
for i in array:
if i > max:
...
and
array.remove(max)
So, you have 3×N comparisons, plus 3x removal. I guess the removal is optimized in C, but there is again about 3×(N/2) comparisons to find the item to be removed.
So, a total of approximately 4.5 × N comparisons.
The other solution
The other solution goes through the list only once, but each time it compares to the three elements in sortedLargest:
for i in reversed(range(len(sortedLargest))):
...
and almost each time it sorts the sortedLargest with these three assignments:
array[0] = array[1]
array[idx-1] = array[idx]
array[idx] = element
So, you are N times:
calling check
creating and reversing a range(3)
accessing sortedLargest[i]
comparing num > sortedLargest[i]
calling shift
comparing idx == 0
and about 2×N/3 times doing:
array[0] = array[1]
array[idx-1] = array[idx]
array[idx] = element
and N/3 times array[0] = element
It is difficult to count, but that is much more than 4.5×N comparisons.

python- Solving Round Table (ZCO,2012)

N knights are sitting in a circle. Making a dessert for knight i costs C[i]. Find the minimum cost such that for every pair of adjacent knights, at least one gets his dessert. N ≤ 10 ** 6.
Input
There are 2 lines of input. The first line contains a single integer N, the number of seats at the table. The next line contains N space-separated integers, each being the cost of the dessert of a Knight, listed in counterclockwise order around the table.
Output
The output should be a single line containing a single integer, the minimum possible cost for you, the chef.
Problem reference:https://www.codechef.com/ZCOPRAC/problems/ZCO12004
.I have tried this using DP, my code
n=int(input())
a=[int(i) for i in input().split()]
def ram(x):
m=x[0]
k=0
for i in range(2,n):
if k==0:
m+=min(x[i],x[i-1])
if min(x[i],x[i-1]) ==x[i]:
k=1
else:
k=0
else:
k=0
continue
return m
b1=ram(a)
a.insert(0,a[n-1])
a.pop(n)
b2=ram(a)
print(min(b1,b2))
But unfortunately, this is a wrong answer, please find the fault.It is advised to consider time complexity, less than 1 sec.
edit:
n=int(input())
a=[int(i) for i in input().split()]
cost1=cost2=[]
if n==1:
print(a[0])
elif n==2:
print(min(a[0],a[1]))
else:
cost1.append(a[0])
cost1.append(a[1])
for j in range(2,n):
cost1.append(a[j]+min(cost1[j-1],cost1[j-2]))
cost2.append(a[n-1])
cost2.append(a[n-2])
for k in range(2,n):
cost2.append(a[n-k-1]+min(cost2[k-1],cost2[k-2]))
print(min(cost1[n-1],cost2[n-1]))
This solution to this problem basically has to take care of 2 states.
Consider you are currently at index i. Now you have to decide whether you want to select the element of index i in your final sum.
The states are as follows:
1) If you decide that element at index i should included in final sum, then it does not matter that the element at previous index, i.e. i-1, is included or not.
2) If you decide that element at index i should not be included in final sum, then it is mandatory that the element at previous index, i.e. i-1, is included.
In your solution, you are taking care of only state 1, but not of state 2. So you will have to maintain 2 variables for optimal intermediate answers at each index.
Here is the sample code:
function calculate(int arr[], int start, int end){
dp[start][0] = arr[start];
dp[start][1] = 0LL;
for(int i=start+1;i<=end;i++){
dp[i][1] = dp[i-1][0]; //State 2
dp[i][0] = arr[i] + min( dp[i-1][1], dp[i-1][0] ); //State 1
}
return min( dp[end][0], dp[end][1] );
}
Note: dp array is a 2D array that stores the intermediate optimal answers.
dp[i][1] = Optimal answer by not including the element.
dp[i][0] = Optimal answer by including the element.

Categories

Resources