LeetCode: Maximum Subarray

自己想得太复杂了,网上查了别人的代码。。太简单了。。

 1 class Solution {

 2 public:

 3     int maxSubArray(int A[], int n) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         int sum = 0;

 7         int ret = INT_MIN;

 8         for(int i = 0 ; i < n; ++i) {

 9             sum += A[i];

10             ret = max(ret, sum);

11             sum = max(sum, 0);

12         }

13         return ret;

14     }

15 };

 C#

 1 public class Solution {

 2     public int MaxSubArray(int[] nums) {

 3         int sum = 0;

 4         int ans = Int32.MinValue;

 5         for (int i = 0; i < nums.Length; i++) {

 6             sum += nums[i];

 7             ans = Math.Max(ans, sum);

 8             sum = Math.Max(sum, 0);

 9         }

10         return ans;

11     }

12 }
View Code

 

你可能感兴趣的:(LeetCode)