How to resolve the algorithm Greatest subsequential sum step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Greatest subsequential sum step by step in the Swift programming language

Table of Contents

Problem Statement

Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.

An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Greatest subsequential sum step by step in the Swift programming language

Source code in the swift programming language

func maxSubseq(sequence: [Int]) -> (Int, Int, Int) {
    var maxSum = 0, thisSum = 0, i = 0
    var start = 0, end = -1
    for (j, seq) in sequence.enumerated() {
        thisSum += seq
        if thisSum < 0 {
            i = j + 1
            thisSum = 0
        } else if (thisSum > maxSum) {
            maxSum = thisSum
            start = i
            end = j
        }
    }
    return start <= end && start >= 0 && end >= 0
        ? (start, end + 1, maxSum) : (0, 0, 0)
}

let a = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
let (start, end, maxSum) = maxSubseq(sequence: a)
print("Max sum = \(maxSum)")
print(a[start..<end])


  

You may also check:How to resolve the algorithm Date manipulation step by step in the Fantom programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the Haxe programming language
You may also check:How to resolve the algorithm 9 billion names of God the integer step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm Munchausen numbers step by step in the BASIC programming language
You may also check:How to resolve the algorithm Hello world/Standard error step by step in the Wren programming language