import java.util.*; public class Kadane { private static int kadne(int[] nums){ /* int prev, history; prev = history = nums[0]; */ int prev = nums[0], history = nums[0]; for(int i = 1; i<nums.length; i++){ prev = Math.max(nums[i], nums[i]+ prev); history = Math.max(prev, history); System.out.println(prev+" "+history+"\n"); } return history; } public static void main(String args[]) { int [] nums = {-2,1,-3,4,-1,2,1,-5,4}; int res = kadne(nums); System.out.println("Maximum: "+res); } } > java -cp /tmp/CSqCzH62b6 Kadane 1 1 -2 1 4 4 3 4 5 5 6 6 1 6 5 6 Maximum: 6
Python
1 2 3 4 5 6
def kadane(nums): history = prev = nums[0] for i in range(1, len(nums)): prev = max( nums[i], nums[i]+ prev) # local maximum history = max(prev, history) return history