您的位置:首页 > 其它

Leetcode 53. Maximum Subarray

2015-03-10 17:42 429 查看
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array
[−2,1,−3,4,−1,2,1,−5,4]
,

the contiguous subarray
[4,−1,2,1]
has the largest sum =
6
.

click to show more practice.

More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

[Solution]
dynamic programming:
let local_suffix[0...i....n] represet max subarray contains the ith number in A[],

if (local_suffix[i - 1] <= 0)
  local_suffix[i] = A[i - 1];
else
  local_suffix[i] = local_suffix[i - 1] + A[i - 1];


int maxSubArray(int A[], int n)
{
if (n <= 0)
return -1;
int global_suffix = INT_MIN, *local_suffix = new int[n + 1];

local_suffix[0] = 0;
for (int i = 1; i <= n; i++)
{
if (local_suffix[i - 1] <= 0)
local_suffix[i] = A[i - 1];
else
local_suffix[i] = local_suffix[i - 1] + A[i - 1];

if (global_suffix < local_suffix[i])
global_suffix = local_suffix[i];
}

delete[] local_suffix;
return global_suffix;
}


However, this uses O(n) memory. We can use just local_suffix instead.

int maxSubArray(int A[], int n)
{
if (n <= 0)
return -1;
int global_suffix = INT_MIN, local_suffix;

for (int i = 0; i < n; i++)
{
if (local_suffix <= 0)
local_suffix = A[i];
else
local_suffix = local_suffix + A[i];

if (global_suffix < local_suffix)
global_suffix = local_suffix;
}

return global_suffix;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: