Search
 
SCRIPT & CODE EXAMPLE
 

CPP

kadane algorithm

public int kadane(int[] arr){
	int max_so_far = 0, curr_max = Integer.MIN_VALUE;
    for(int i: arr){
    	max_so_far += i;
        if(max_so_far<0) max_so_far = 0;
        if(max_so_far>curr_max) curr_max = max_so_far;
    }
    return curr_max;
}
Comment

kadane algorithm

Lets take the example:
    {-2, -3, 4, -1, -2, 1, 5, -3}

    max_so_far = max_ending_here = 0

    for i=0,  a[0] =  -2
    max_ending_here = max_ending_here + (-2)
    Set max_ending_here = 0 because max_ending_here < 0

    for i=1,  a[1] =  -3
    max_ending_here = max_ending_here + (-3)
    Set max_ending_here = 0 because max_ending_here < 0

    for i=2,  a[2] =  4
    max_ending_here = max_ending_here + (4)
    max_ending_here = 4
    max_so_far is updated to 4 because max_ending_here greater 
    than max_so_far which was 0 till now

    for i=3,  a[3] =  -1
    max_ending_here = max_ending_here + (-1)
    max_ending_here = 3

    for i=4,  a[4] =  -2
    max_ending_here = max_ending_here + (-2)
    max_ending_here = 1

    for i=5,  a[5] =  1
    max_ending_here = max_ending_here + (1)
    max_ending_here = 2

    for i=6,  a[6] =  5
    max_ending_here = max_ending_here + (5)
    max_ending_here = 7
    max_so_far is updated to 7 because max_ending_here is 
    greater than max_so_far

    for i=7,  a[7] =  -3
    max_ending_here = max_ending_here + (-3)
    max_ending_here = 4
Comment

kadane algo

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int curMax = 0, maxTillNow = INT_MIN;
        for(auto c : nums)
            curMax = max(c, curMax + c),
            maxTillNow = max(maxTillNow, curMax);
        return maxTillNow;
    }
};
Comment

PREVIOUS NEXT
Code Example
Cpp :: c++ fstream read line write ,creat file program 
Cpp :: strcmp in c++ header file 
Cpp :: Variabili globali c++ 
Cpp :: reverse the number codechef solution in c++ 
Cpp :: cpp how to add collisions to boxes 
Cpp :: what is xor_eq c++ 
Cpp :: vector and algorithm 
Cpp :: c++ restrict template types 
Cpp :: sort an array using stl 
Cpp :: progress bar custom color c++ buider 
Cpp :: A Subtask Problem codechef solution in cpp 
Cpp :: viewlist exaple win32 
Cpp :: . Single-line comments start with two forward slashes (//). 
Cpp :: find with hash set 
Cpp :: comentar todas linhas de uma vez vs code 
Cpp :: Hash Sort in C++ 
Cpp :: what does npl mean? 
Cpp :: c++ hide credentials 
Cpp :: c++ trim string 
Cpp :: c++ poitner 
Cpp :: c++ thread id 
Cpp :: what is require to run min max function on linux in cpp 
Cpp :: pros millis() 
Cpp :: c++ map access 
Cpp :: how to show c++ binary files in sublime text 
Cpp :: multiple objects in vector C++ 
Cpp :: c++ program to use nmap 
Cpp :: Jython Java Python 
Cpp :: random 1 diem tren man hinh bang dev c 
Cpp :: The iostream is the head er file which contains all the functions of program like cout, cin and etc. 
ADD CONTENT
Topic
Content
Source link
Name
7+9 =