题目:

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.

题解:

  遍历所有组合,更新最大和。

Solution 1 (TLE)

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size(), result = nums[];
for(int i=; i<n; ++i) {
int tmp = nums[i];
result = max(tmp,result);
for(int j=i+; j<n; ++j) {
tmp += nums[j];
result = max(tmp,result);
}
}
return result;
}
};

  可以看做动态规划的简略版,见Solution 5

Solution 2 ()

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size(), result = nums[], tmp = ;
for(int i=; i<n; ++i) {
tmp = max(tmp + nums[i], nums[i]);
result = max(result, tmp);
}
return result;
}
};

  贪心算法:The idea is to find the largest difference between the sums when you summing up the array from left to right. The largest difference corresponds to the sub-array with largest sum

Solution 3 ()

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = , minsum = , result = nums[], n = nums.size();
for(int i = ; i < n; i++) {
sum += nums[i];
if(sum - minsum > res) result = sum - minsum;
if(sum < minsum) minsum = sum;
}
return result;
}
};

  分治法:

Solution 4 ()

  DP算法:维护一个一维数组。

Solution 5 ()

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n,);//dp[i] means the maximum subarray ending with nums[i];
dp[] = nums[];
int max = dp[]; for(int i = ; i < n; i++){
dp[i] = nums[i] + (dp[i - ] > ? dp[i - ] : );
max = Math.max(max, dp[i]);
}
return max;
}
};

最新文章

  1. Visual Studio Code 配置指南
  2. MongoDB学习笔记一—简介
  3. 解决安卓微信浏览器中location.reload 或者 location.href失效的问题
  4. WordPress基础:订阅源rss的使用
  5. 纸上谈兵:堆(heap)
  6. lost+found目录
  7. JDBC Connection
  8. Cocos2d-x标签文乱码问题
  9. Oracle 异常处理
  10. shell中exit命令不退出脚本
  11. hdu Repositoryti
  12. Https握手协议以及证书认证
  13. Python巡检Oracle表空间并邮件告警
  14. mvc中html导出成word下载-简单粗暴方式
  15. 使用HttpClient4.5实现HTTPS的双向认证
  16. Ubuntu 硬盘分区只读,重新挂载为读写分区之后,文件依然创建出错
  17. mysql创建外键注意事项
  18. C语言--第二周作业评分和总结(5班)
  19. Mysql 根据id查所有父级或子级
  20. linux-2.6.22.6内核启动分析之head.S引导段代码

热门文章

  1. hdu1316
  2. Pandoc PDF 中文
  3. pm2 服务崩溃 Error: bind EADDRINUSE
  4. React中key的必要性与使用
  5. Android-解决Fail to post notification on channel &quot;null&quot;的方法
  6. COGS1817. [WC2013]糖果公园
  7. 解决集群搭建找不到datanode的问题
  8. Linux内核的编译安装
  9. Quartz Job scheduling 基础实现代码
  10. ubuntu下安装redis以及redis客户端在mac下的使用