Maximum Subarray sum - Where is my solution wrong? Kadanes Algorithm

2024/11/18 11:27:00

Here is a description of the problem:

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.

My solution so far is:

def max_sequence(arr):
sum = 0
max = 0
for i in arr:sum += iif i > max:max = isum = maxelif sum > max:max = sumreturn(max)

It works on simple examples but not on random ones... Could you please help me where I made a mistake / what I didn't consider?

see the output from Codewars

Answer

this may be an alternative approach of doing it:

def consequtive_sub_lists(l): sublists = []for iter, item in enumerate(l):sublists.append([item])cur_sublist = [item]for idx in range(iter+1, len(l)):cur_sublist.append(l[idx])sublists.append(cur_sublist.copy())return sublistssublists = consequtive_sub_lists([1,2,-3,4])
max_sum, max_list = max([(sum(item), item) for item in sublists])
print(f"max_sum: {max_sum}")
print(f"max_list: {max_list}")

output:

max_sum: 4
max_list: [4]

Some Explanations: I sepparated the solution into 2 main steps:

  • create all consequtive sub_lists out of given list (as list of lists)
  • out of it, find out the element that has the maximum sum over it's elements

For the Kadane's algorithm (to make it similar to the solution in here)

def max_sequence(arr):max = 0sum = 0for i in arr:sum += iif sum > max:max = sumif sum < 0:sum = 0return max

this one is work

https://en.xdnf.cn/q/118681.html

Related Q&A

Pandas: Selecting rows and columns based on a subset of columns that contain a certain value

Lets say I have a dataframe with column names as follows:col_id_1, col_id_2, ..., col_id_m, property_1, property_2 ..., property_nAs an example, how would I search across all col_ids for, say, the valu…

Open a image file then display it in new window

I have a button in my GUI then after selecting a image file I want it to display in new window.Code:import tkinter as tk from tkinter import * from tkinter import ttk from tkinter import filedialog …

python plotting chart in interactive viewer vscode

This works and shows a plot in vscode: #%% cell with plot import matplotlib.pyplot as plt y = [3.2, 3.9, 3.7, 3.5, 3.02199] x = [0.15, 0.3, 0.45, 0.6, 0.75] n = [155, "outliner", 293, 230, 67…

Find all lines in a dataframe that matches specific pattern and extract the strings after split

I have a dataframe that looks like LineEntry: [0x0000000002758261-0x0000000002758268): /a/b/c:7921:14 LineEntry: [0x0000000002756945-0x0000000002756960): /f/b/c:6545:10 LineEntry: [0x00000000027562c9-0…

Python: Concatenate many dicts of numpy arrays with same keys and size

I have a function called within a loop that returns a dict (dsst_mean) with roughly 50 variables. All variables are numpy arrays of length 10.The loop iterates roughly 3000 times. Im current concatenat…

intersection of 2 objects of different types

i want to take the intersection of: ((e, 13.02338360095244), (a, 11.820318700775383), (o, 9.20172171683253), (s, 7.635081506807498), (n, 7.547469320471335), (i, 7.219915745772025), (r, 6.70492704072287…

Enemy Projectiles Attack Way To Fast Problem

I am trying to make my enemy bullets attack the player but its attacking way to fast I dont know why VIDEO my enemy bullets class# enemys bulletsksud = pygame.image.load("heart.png")class Boo…

How to find the maximum digit of an integer? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 10 years ago.This p…

How to use python to generate a magazine cover? [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Why do I get this error? NoneType object has no attribute shape in opencv

Im working on real-time clothing detection. so i borrowed the code from GitHub like this:https://github.com/rajkbharali/Real-time-clothes-detection but (H, W) = frame.shape[:2]:following error in last …