博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Maximum Subarray
阅读量:4553 次
发布时间:2019-06-08

本文共 1677 字,大约阅读时间需要 5 分钟。

class Solution {public:    int maxSubArray(int A[], int n) {        int cur_sum = 0;        int max_sum = INT_MIN;                for (int i=0; i
max_sum) max_sum = cur_sum; if (cur_sum < 0) { cur_sum = 0; } } return max_sum; }};

老题

第二轮:

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.

理解就不用记了,更简洁一些的做法依照公式:f(n) = max(f(n-1) + A[0], A[0])

class Solution {public:    int maxSubArray(int A[], int n) {        if (A == NULL || n < 1) {            return INT_MIN;        }        int contsum = A[0];        int maxsum = A[0];                for (int i=1; i

分治法,nlogn, 但是TLE

class Solution {public:int maxSubArray(int A[], int n) {        return dfs(A, 0, n);    }        int dfs(int A[], int start, int end) {        if (start >= end) {            cout<<"range error: start="<
<<", end="<
<
mb ? ma : mb; int lsum = 0, rsum = 0; int lmax = INT_MIN, rmax = INT_MIN; for (int i=mid - 1; i>=0; i--) { lsum += A[i]; if (lsum > lmax) lmax = lsum; } for (int i=mid; i
rmax) rmax = rsum; } if (lmax + rmax > maxsum) maxsum = lmax + rmax; return maxsum; };};

转载于:https://www.cnblogs.com/lailailai/p/3854124.html

你可能感兴趣的文章
一点小问题
查看>>
pytest 10 skip跳过测试用例
查看>>
MVC身份验证及权限管理
查看>>
It was not possible to find any compatible framework version
查看>>
gulp与webpack的区别
查看>>
offset--BUG
查看>>
CSS选择器
查看>>
POJ_3667 线段树+lazy (线段树经典题)
查看>>
Android获取图片资源的4种方式
查看>>
找工作---操作系统常考知识点总结【PB】
查看>>
解决ionic <ion-nav> rootParams获取不到参数
查看>>
Python学习02 列表 List
查看>>
[DOM Event Learning] Section 3 jQuery事件处理基础 on(), off()和one()方法使用
查看>>
python爬虫-淘宝商品密码(图文教程附源码)
查看>>
centos6.3下如何搭建LAMP环境
查看>>
C#的一些基础内容
查看>>
nodejs概述
查看>>
H3C PAP验证配置示例
查看>>
oracle-Dbca数据库模板
查看>>
ionic 轮播
查看>>