• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

LeetCodeOnlineJudge题目C#练习-MaximumSubarray

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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.
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.

 1         public static int MaximumSubarray(int[] A)
 2         {
 3             int n = A.Length;
 4             int max = A[0], max_neg = A[0], sum = 0;
 5             bool flag = false; // for all the elements are negative integers
 6             for (int i = 0; i < n; i++)
 7             {
 8                 //if found one is not negative, toggle flag. And keep tracking the max negative number
 9                 if (A[i] >= 0)
10                     flag = true;
11                 else if (A[i] > max_neg)
12                     max_neg = A[i];
13 
14                 sum += A[i];
15                 if (sum < 0)
16                     sum = 0;
17                 else if (sum > max)
18                     max = sum;
19             }
20 
21             return flag ? max : max_neg;
22         }

代码分析:

  O(n)的解法, 要注意所有element都是negative的case。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#:使用dsoframer.ocx控件实现内嵌office效果(详解)发布时间:2022-07-13
下一篇:
C#多线程学习(三)生产者和消费者发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap