-2

Given a list. I have to create sublists having at least one element, and then return the sublist having maximum sum.

here is what I tried :

class Solution:
def maxSubArray(self, nums: List[int]) -> int:
    lists=[[]]

    for i in range(1,len(nums)+1):
        for j in range(1,i):
            lists.append(nums[j:i])
    new_list=lists
    sum_list=[]
    for k in range(1,len(new_list)):
        sum1=sum(new_list[k])
        sum_list.append(sum1)
    return max(sum_list)

this is giving this error :

ValueError: max() arg is an empty sequence

How do I tweek my code to remove the empty sublist.

  • A typo? `lists=[]` – sagi Feb 10 '22 at 12:53
  • Also, I'm not sure `new_list=lists` is [doing what you think it does](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it) – DeepSpace Feb 10 '22 at 12:53

1 Answers1

0

You can check if the list is empty before applying the max() method like this:

class Solution:
def maxSubArray(self, nums: List[int]) -> int:
    lists=[[]]

    for i in range(1,len(nums)+1):
        for j in range(1,i):
            lists.append(nums[j:i])
    new_list=lists
    sum_list=[]
    for k in range(1,len(new_list)):
        sum1=sum(new_list[k])
        sum_list.append(sum1)
    if sum_list:
        return max(sum_list)
    else:
        return 0  # or some default value you want
Filipe S.
  • 74
  • 5