SlideShare a Scribd company logo
Kadane’s continuous subarray algorithm




rerun.me   by Arun Manivannan
Maximum sum subarray problem
                       - find the contiguous subarray who has the maximum sum

                                                                               all you need to do is need to




                         {
                                                                                         find me




             -1    3        -5       4        6       -1       2        -7        13        -3



             0     1        2        3        4        5       6        7         8          9




rerun.me
This program introduces few variables on top of the default implementation of Kadane’s
    algorithm.

    We’ll have four major variables in all

      1) cumulative sum - holds the cumulative sum of the array

      2) maximum sum - holds the maximum sum of continuous items in the array.

      3) maximum start index - start index of the sub array whose total is the maximum within
      the array

      4) maximum end index - end index of the sub array whose total is the maximum within the
      array



rerun.me
Let’s take a sample bag of numbers
                                   stored in an array



           -1   3   -5        4      6      -1      2         -7   13   -3



           0    1   2         3      4       5      6         7    8    9




                                                                             index



rerun.me
cum sum 0
           max sum Integer.MIN_VALUE


             -1     3        -5   4    6   -1   2   -7   13   -3



             0      1        2    3    4   5    6   7    8    9


           current index 0
           lower index 0
           end index 0



rerun.me
cum sum -1         Keep incrementing our cumulative sum
                max sum -1


           -1    3      -5     4        6     -1      2      -7     13    -3



           0      1     2      3        4      5      6      7      8     9



                current index 0
                startIndex 0
                end index 0
                maxStartIndexUntilNow -1

rerun.me
When the cumulative sum is greater than max sum, it just
                                         means that the next number is an ‘useful addition’.
                                                           So, lets set our
                                              max sum as our current cumulative sum,
                                           startIndex as the maxStartIndexUntilNow and
                           cum sum 2                  endIndex as our counter.
           prev max sum -1 max sum 2                                 if(cumulativeSum>maxSum){
                                                                         maxSum = cumulativeSum;
                                                                         maxStartIndex=maxStartIndexUntilNow;
                                                                         maxEndIndex = currentIndex;
                                                                     }




               -1     3     -5     4     6        -1        2        -7          13            -3



                0     1     2      3     4         5        6        7            8             9


                          current index 1
                          startIndex 0
                          end index 1
                          maxStartIndexUntilNow 0


rerun.me
When the cumulative sum is <0, it means that the next
                                           number is negative and actually bringing down the total sum.
                                               So, reset the cumulative sum as zero to restart the
                                                      accumulation process from next number.
                                           Also, let’s set the fresh maxStartIndexUntilNow to the next
                                                        number to reflect fresh accumulation
            actual cum sum -3 cum sum 0
                                                                 else if (cumulativeSum<0){
                              max sum 2                          	
                                                                 	
                                                                     maxStartIndexUntilNow=currentIndex+1;
                                                                     cumulativeSum=0;
                                                                 }




           -1    3      -5     4       6         -1        2        -7           13            -3



           0     1      2      3       4         5         6         7            8             9


                             current index 2         That said, don’t bother reseting the endIndex or
                             startIndex 0       startIndex or the maxSum. Instead save them aside since
                             end index 1         there could be no series in the future which has a sum
                                                                more than the one thus far.
                             maxStartIndexUntilNow 3


rerun.me
Ahaa, looks like our new cumulative sum is more than
                                                  our max sum - let’s set our new max sum, new
                                                               startIndex and end Index.

                                                our new ‘max’ end index would simply be our current
                                               Index. Our startIndex is just our ‘saved away’ startIndex
                                    cum sum 4                    if(cumulativeSum>maxSum){

                     prev max sum 2 max sum 4                        maxSum = cumulativeSum;
                                                                     maxStartIndex=maxStartIndexUntilNow;
                                                                     maxEndIndex = currentIndex;
                                                                 }




           -1   3        -5      4       6      -1       2         -7            13            -3



           0    1         2      3       4      5        6          7             8            9


                                        current index 3
                    prev startIndex 0   startIndex 3
                    prev endIndex 1     end index 3
                                        maxStartIndexUntilNow 3


rerun.me
More Good news coming along. cumulative sum is
                                  increasing and is getting more than the max sum every
                                     iteration. As before, reset max sum, end Index and
                                                           startIndex

                                 cum sum 10
                                 max sum 10


           -1   3   -5   4   6    -1       2        -7       13        -3



           0    1   2    3   4    5        6         7        8        9


                                 current index 4
                                 startIndex 3
                                 end index 4
                                 maxStartIndexUntilNow 3


rerun.me
A little loss here. However, our max sum is stronger
                than the cumulative sum still. So, let’s just ignore it and
                                       do nothing.


                                                                       cum sum 9
                                                                       max sum 10


           -1        3          -5         4         6         -1         2       -7   13    -3



           0          1         2          3         4          5             6   7    8     9


                                                                        current index 5
                                                                        startIndex 3
                                                                        end index 4
                                                                        maxStartIndexUntilNow 3


rerun.me
Let’s gobble up the next increment to the sum. Make
                          max sum and end index reflect it.


                                                prev cum sum 9 cum sum 11
                                                               max sum 11


           -1   3        -5        4        6        -1        2       -7    13     -3



           0    1         2        3        4         5        6       7      8      9


                                                                      current index 6
                                                                      startIndex 3
                                                                      end index 6
                                                                      maxStartIndexUntilNow 3


rerun.me
A setback here but we have our savings - max indices
                  and sum. Let’s pretend that this never happened.


                                                           prev cum sum 11 cum sum 4
                                                                           max sum 11


           -1    3        -5       4         6        -1        2      -7    13     -3



           0     1        2        3         4        5         6      7     8      9


                                                                            current index 7
                                                                            startIndex 3
                                                                            end index 6
                                                                            maxStartIndexUntilNow 3


rerun.me
Goodness !!!


                                                            cum sum 17
                                                            max sum 17



           -1   3   -5   4    6        -1   2   -7     13    -3



           0    1   2    3    4         5   6   7      8      9

                                                            current index 8
                                                            startIndex 3
                                                            end index 8
                                                     maxStartIndexUntilNow 3

rerun.me
A final drop. But hey, we’ve passed the maximum in the
                       last pass. Let’s ignore this pass and return the previous
                                                  results.

                                                                                               cum sum 14
                                                                                               max sum 17



           -1      3      -5        4         6         -1        2         -7     13     -3



           0       1       2         3         4        5         6         7      8      9

                                                                                               current index 9
                The contiguous array which has the maximum sum is                              startIndex 3
                sandwiched within the 3rd and the 8th indices.                                 end index 8

                The maximum sum of the contiguous array is 17                      maxStartIndexUntilNow 3

rerun.me

More Related Content

What's hot

Circular queue
Circular queueCircular queue
linear probing
linear probinglinear probing
linear probing
rajshreemuthiah
 
Maximum sum subarray
Maximum sum subarrayMaximum sum subarray
Maximum sum subarray
Shaheen kousar
 
Bubble sort
Bubble sortBubble sort
Bubble sort
Manek Ar
 
Data Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge SortData Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge Sort
ManishPrajapati78
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
Syed Zaid Irshad
 
Digital Search Tree
Digital Search TreeDigital Search Tree
Digital Search Tree
East West University
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
MAHALAKSHMI P
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
Then Murugeshwari
 
12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS
koolkampus
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap Sort
Mohammed Hussein
 
Binary tree
Binary treeBinary tree
Binary tree
Rajendran
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
Tirthika Bandi
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
sandeep54552
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
shameen khan
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
Vardhil Patel
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of Algorithms
Drishti Bhalla
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
Master theorem
Master theoremMaster theorem
Master theorem
fika sweety
 
Graph data structure and algorithms
Graph data structure and algorithmsGraph data structure and algorithms
Graph data structure and algorithms
Anandhasilambarasan D
 

What's hot (20)

Circular queue
Circular queueCircular queue
Circular queue
 
linear probing
linear probinglinear probing
linear probing
 
Maximum sum subarray
Maximum sum subarrayMaximum sum subarray
Maximum sum subarray
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Data Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge SortData Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge Sort
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Digital Search Tree
Digital Search TreeDigital Search Tree
Digital Search Tree
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap Sort
 
Binary tree
Binary treeBinary tree
Binary tree
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of Algorithms
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
Master theorem
Master theoremMaster theorem
Master theorem
 
Graph data structure and algorithms
Graph data structure and algorithmsGraph data structure and algorithms
Graph data structure and algorithms
 

Viewers also liked

Corpus Christi En Carcaboso.
Corpus Christi En Carcaboso.Corpus Christi En Carcaboso.
Corpus Christi En Carcaboso.
montemorcillo
 
Datos Del Sistema Solar
Datos Del Sistema SolarDatos Del Sistema Solar
Datos Del Sistema Solarmontemorcillo
 
Indianapolis Book Unveiling 2008
Indianapolis Book Unveiling 2008Indianapolis Book Unveiling 2008
Indianapolis Book Unveiling 2008
Who's Who Publishing
 
EWSN'15 Industry Session - Francesco Flammini (Ansaldo STS)
EWSN'15 Industry Session - Francesco Flammini (Ansaldo STS)EWSN'15 Industry Session - Francesco Flammini (Ansaldo STS)
EWSN'15 Industry Session - Francesco Flammini (Ansaldo STS)
Francesco Flammini
 
Esrel08 Final
Esrel08 FinalEsrel08 Final
Esrel08 Final
Francesco Flammini
 
ACIVS'12: Evaluating the effects of MJPEG compression on Motion Tracking in m...
ACIVS'12: Evaluating the effects of MJPEG compression on Motion Tracking in m...ACIVS'12: Evaluating the effects of MJPEG compression on Motion Tracking in m...
ACIVS'12: Evaluating the effects of MJPEG compression on Motion Tracking in m...
Francesco Flammini
 

Viewers also liked (7)

Corpus Christi En Carcaboso.
Corpus Christi En Carcaboso.Corpus Christi En Carcaboso.
Corpus Christi En Carcaboso.
 
Uiui444
Uiui444Uiui444
Uiui444
 
Datos Del Sistema Solar
Datos Del Sistema SolarDatos Del Sistema Solar
Datos Del Sistema Solar
 
Indianapolis Book Unveiling 2008
Indianapolis Book Unveiling 2008Indianapolis Book Unveiling 2008
Indianapolis Book Unveiling 2008
 
EWSN'15 Industry Session - Francesco Flammini (Ansaldo STS)
EWSN'15 Industry Session - Francesco Flammini (Ansaldo STS)EWSN'15 Industry Session - Francesco Flammini (Ansaldo STS)
EWSN'15 Industry Session - Francesco Flammini (Ansaldo STS)
 
Esrel08 Final
Esrel08 FinalEsrel08 Final
Esrel08 Final
 
ACIVS'12: Evaluating the effects of MJPEG compression on Motion Tracking in m...
ACIVS'12: Evaluating the effects of MJPEG compression on Motion Tracking in m...ACIVS'12: Evaluating the effects of MJPEG compression on Motion Tracking in m...
ACIVS'12: Evaluating the effects of MJPEG compression on Motion Tracking in m...
 

Recently uploaded

GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 

Recently uploaded (20)

GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 

Kadane's continuous subarray algorithm

  • 1. Kadane’s continuous subarray algorithm rerun.me by Arun Manivannan
  • 2. Maximum sum subarray problem - find the contiguous subarray who has the maximum sum all you need to do is need to { find me -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 rerun.me
  • 3. This program introduces few variables on top of the default implementation of Kadane’s algorithm. We’ll have four major variables in all 1) cumulative sum - holds the cumulative sum of the array 2) maximum sum - holds the maximum sum of continuous items in the array. 3) maximum start index - start index of the sub array whose total is the maximum within the array 4) maximum end index - end index of the sub array whose total is the maximum within the array rerun.me
  • 4. Let’s take a sample bag of numbers stored in an array -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 index rerun.me
  • 5. cum sum 0 max sum Integer.MIN_VALUE -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 0 lower index 0 end index 0 rerun.me
  • 6. cum sum -1 Keep incrementing our cumulative sum max sum -1 -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 0 startIndex 0 end index 0 maxStartIndexUntilNow -1 rerun.me
  • 7. When the cumulative sum is greater than max sum, it just means that the next number is an ‘useful addition’. So, lets set our max sum as our current cumulative sum, startIndex as the maxStartIndexUntilNow and cum sum 2 endIndex as our counter. prev max sum -1 max sum 2 if(cumulativeSum>maxSum){ maxSum = cumulativeSum; maxStartIndex=maxStartIndexUntilNow; maxEndIndex = currentIndex; } -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 1 startIndex 0 end index 1 maxStartIndexUntilNow 0 rerun.me
  • 8. When the cumulative sum is <0, it means that the next number is negative and actually bringing down the total sum. So, reset the cumulative sum as zero to restart the accumulation process from next number. Also, let’s set the fresh maxStartIndexUntilNow to the next number to reflect fresh accumulation actual cum sum -3 cum sum 0 else if (cumulativeSum<0){ max sum 2 maxStartIndexUntilNow=currentIndex+1; cumulativeSum=0; } -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 2 That said, don’t bother reseting the endIndex or startIndex 0 startIndex or the maxSum. Instead save them aside since end index 1 there could be no series in the future which has a sum more than the one thus far. maxStartIndexUntilNow 3 rerun.me
  • 9. Ahaa, looks like our new cumulative sum is more than our max sum - let’s set our new max sum, new startIndex and end Index. our new ‘max’ end index would simply be our current Index. Our startIndex is just our ‘saved away’ startIndex cum sum 4 if(cumulativeSum>maxSum){ prev max sum 2 max sum 4 maxSum = cumulativeSum; maxStartIndex=maxStartIndexUntilNow; maxEndIndex = currentIndex; } -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 3 prev startIndex 0 startIndex 3 prev endIndex 1 end index 3 maxStartIndexUntilNow 3 rerun.me
  • 10. More Good news coming along. cumulative sum is increasing and is getting more than the max sum every iteration. As before, reset max sum, end Index and startIndex cum sum 10 max sum 10 -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 4 startIndex 3 end index 4 maxStartIndexUntilNow 3 rerun.me
  • 11. A little loss here. However, our max sum is stronger than the cumulative sum still. So, let’s just ignore it and do nothing. cum sum 9 max sum 10 -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 5 startIndex 3 end index 4 maxStartIndexUntilNow 3 rerun.me
  • 12. Let’s gobble up the next increment to the sum. Make max sum and end index reflect it. prev cum sum 9 cum sum 11 max sum 11 -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 6 startIndex 3 end index 6 maxStartIndexUntilNow 3 rerun.me
  • 13. A setback here but we have our savings - max indices and sum. Let’s pretend that this never happened. prev cum sum 11 cum sum 4 max sum 11 -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 7 startIndex 3 end index 6 maxStartIndexUntilNow 3 rerun.me
  • 14. Goodness !!! cum sum 17 max sum 17 -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 8 startIndex 3 end index 8 maxStartIndexUntilNow 3 rerun.me
  • 15. A final drop. But hey, we’ve passed the maximum in the last pass. Let’s ignore this pass and return the previous results. cum sum 14 max sum 17 -1 3 -5 4 6 -1 2 -7 13 -3 0 1 2 3 4 5 6 7 8 9 current index 9 The contiguous array which has the maximum sum is startIndex 3 sandwiched within the 3rd and the 8th indices. end index 8 The maximum sum of the contiguous array is 17 maxStartIndexUntilNow 3 rerun.me

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n