Skip to content

Commit

Permalink
Merge pull request pezy#8 from Mooophy/master
Browse files Browse the repository at this point in the history
add solution by devide and conquer
  • Loading branch information
pezy committed Apr 9, 2015
2 parents b0b177e + 44dc59f commit 987518e
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions 014. Maximum Subarray/main.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@ int main()
int A[] = {-2,1,-3,4,-1,2,1,-5,4};
Solution s;
std::cout << s.maxSubArray(A, 9) << std::endl;

SolutionByDivideAndConquer dac;
std::cout << s.maxSubArray(A, 9) << std::endl;

return 0;
}
41 changes: 41 additions & 0 deletions 014. Maximum Subarray/solution.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,44 @@ class Solution {
return maxv;
}
};

class SolutionByDivideAndConquer{
//O(n)
int find_max_crossing_subarray(int arr[], unsigned low, unsigned mid, unsigned hgh)
{
auto accumulation = 0;

auto lft_sum = accumulation = arr[mid];
if (mid > low)
for (auto i = mid - 1; i != low - 1; --i)
if ((accumulation += arr[i]) > lft_sum)
lft_sum = accumulation;

auto rht_sum = accumulation = arr[mid + 1];
if (hgh > mid)
for (auto i = mid + 2; i != hgh + 1; ++i)
if ((accumulation += arr[i]) > rht_sum)
rht_sum = accumulation;

return lft_sum + rht_sum;
}

//O(n lg n)
int divide_and_conquer(int arr[], unsigned low, unsigned hgh)
{
if (low == hgh) return arr[low];

auto mid = (low + hgh) / 2;
auto lft = divide_and_conquer(arr, low, mid);
auto rht = divide_and_conquer(arr, mid + 1, hgh);
auto crs = find_max_crossing_subarray(arr, low, mid, hgh);

return std::max({ lft, rht, crs });
}

public:
int maxSubArray(int A[], int n)
{
return divide_and_conquer(A, 0, n - 1);
}
};

0 comments on commit 987518e

Please sign in to comment.