kadane's algorithm
class Solution { public: int maxProduct(vector<int>& nums) { // Return early if input is empty if (nums.empty()) return 0; int best = INT_MIN; // Running products int maxProd = 1; int minProd = 1; for (int n: nums) { if (n < 0) { // Swap max and min swap(maxProd, minProd); } // Reset to current value if smaller or larger than it // (intuitively means that we start considering a new sub-array) maxProd = max(maxProd*n, n); minProd = min(minProd*n, n); // Update the best best = max(best, maxProd); } return best; } };
Source: leetcode.com
Kadane's algorithm
public static int SumArray() { var arr = new int[]{ -2, -4, -5, -6, -7, -89, -56 }; var sum = 0; var max = arr[0]; foreach (var item in arr) { sum += item; // sum = Math.Max(sum,0); resting here will not give expected output max = Math.Max(sum,max); sum = Math.Max(sum,0); } return max; }
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; }
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
Source: www.geeksforgeeks.org