I feel like Kadane's algorithm is a modified version of the true dynamic programming solution of maximum subarray problem.Why do I feel so? I feel because the way to calculate the maximum subarray can be taken by:
for(i=0;i<N;i++)
{
DP[i][A[i]]=true;
for(j= -ve maximum ;j<= +ve maximum ;j++)
if(DP[i-1][j])
DP[i][j+A[i]]=true;
}
The recurrence being if it is possible to form j with a subarray ending at i-1 elements i can form j+A[i] using the i th element and also form A[i] alone by starting a subarray at i th position And at last we can search this DP array for maximum j that is marked true!
Note : DP[i][j]
represents if it is possible to make j using a sub array ending at i! Here I assume j can be negative too.! Now one can easily derive that sum+ a negative number < sum . That implies adding any negative indices wont help getting a better sum thats why we can drop them! Morover we care about the maximum j till i-1
th position and connect it with i th
element which makes me feel it is kind of making a greedy choice ( Just because maximum + element gives me a maximum).
NOTE: I haven't studied Greedy algorithms by now but I have an idea what a greedy choice is!
EDIT: SOmeone said my algorithm doesn't makes any sense so I am trying to post my code to make myself clear. I haven't taken j as -ve as they aren't fruitful. I repeat my state is defined as is it possible to make j using a subarray ending at i.
#include<bits/stdc++.h>
using namespace std;
int DP[101][101];
int main()
{
int i,j,ans=INT_MIN;
int A[]={3,-1,2,-1,5,-3};
int N=sizeof(A)/sizeof(int);
for(i=1;i<=N;i++)
{
if(A[i-1]>=0)
DP[i][A[i-1]]++;
for(j=0;j<=100;j++)
{
if(DP[i-1][j])
{
if(j+A[i-1]>=0)
DP[i][j+A[i-1]]++;
}
if(DP[i][j])
ans=max(ans,j);
}
}
cout<<ans<<"\n";
return 0;
}
Output 8
dp[i][j]
one by one. – Diuresis