剑指offer--3题
题目:输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18。
第一感觉:看到这道题后,我先想的便是列出所有子数组,求取和再在这些和中求取最大值,这肯定是最简单的了!自己所写的代码如下:
#include "stdafx.h"
#include <iostream> int SubArraySumMax(int arr[], int len); using namespace std; int main(int argc, char* argv[])
{
int arr[] = {, -, , , -, , , -};
int summax = SubArraySumMax(arr,);
cout<<summax<<endl;
return ;
} int SubArraySumMax(int arr[], int len)
{
int i,j;
int summax = ;
int sum_temp;
for(i=; i<len; i++)
{
if(summax < arr[i])
summax = arr[i];
sum_temp = arr[i];
for(j=i+; j<len; j++)
{
sum_temp += arr[j];
if(sum_temp > summax)
summax = sum_temp;
} } return summax;
}
但是这样的思路,其时间复杂度为O(n^2),完全不符合题目所要求的O(n)。自己绞尽脑汁也未能想出更好的办法。。。
在看过标准答案后,惊叹于思想+代码的简单,不过很遗憾,自己并未豁然开朗。
关键未明白为什么可以这样做?根据评论,作者可能使用了所谓“动态规划”(DP)的方法,这应该是数据结构中的知识,看来自己还是井底之蛙,还要继续努力!
标准答案:
// jianzhioffer3.cpp : Defines the entry point for the console application.
// #include "stdafx.h"
#include <iostream>
//int SubArraySumMax(int arr[], int len);
bool FindGreatestSumOfSubArray
(
int *pData, // an array
unsigned int nLength, // the length of array
int &nGreatestSum // the greatest sum of all sub-arrays
);
using namespace std; /*int main(int argc, char* argv[])
{
int arr[] = {1, -2, 3, 10, -4, 7, 2, -5};
int summax = SubArraySumMax(arr,8);
cout<<summax<<endl;
return 0;
} int SubArraySumMax(int arr[], int len)
{
int i,j;
int summax = 0;
int sum_temp;
for(i=0; i<len; i++)
{
if(summax < arr[i])
summax = arr[i];
sum_temp = arr[i];
for(j=i+1; j<len; j++)
{
sum_temp += arr[j];
if(sum_temp > summax)
summax = sum_temp;
} } return summax;
}*/ int main()
{
int arr[] = {, -, , , -, , , -};
int nLength = ;
int nGreatestSum;
bool IfSuccess = FindGreatestSumOfSubArray(arr,nLength,nGreatestSum);
if(IfSuccess)
cout<<nGreatestSum<<endl;
else
cout<<"Input Error!"<<endl;
return ;
} /////////////////////////////////////////////////////////////////////////////
// Find the greatest sum of all sub-arrays
// Return value: if the input is valid, return true, otherwise return false
/////////////////////////////////////////////////////////////////////////////
bool FindGreatestSumOfSubArray
(
int *pData, // an array
unsigned int nLength, // the length of array
int &nGreatestSum // the greatest sum of all sub-arrays
)
{
// if the input is invalid, return false
if((pData == NULL) || (nLength == ))
return false; int nCurSum = nGreatestSum = ;
for(unsigned int i = ; i < nLength; ++i)
{
nCurSum += pData[i]; // if the current sum is negative, discard it
if(nCurSum < )
nCurSum = ; // if a greater sum is found, update the greatest sum
if(nCurSum > nGreatestSum)
nGreatestSum = nCurSum; } // if all data are negative, find the greatest element in the array
if(nGreatestSum == )
{
nGreatestSum = pData[];
for(unsigned int i = ; i < nLength; ++i)
{
if(pData[i] > nGreatestSum)
nGreatestSum = pData[i];
}
} return true;
}
PS:理解DP后,再来解决它!
剑指offer--3题的更多相关文章
- 剑指 offer 第一题: 二维数组中的查找
打算写 图解剑指 offer 66 题 的系列文章,不知道大家有没有兴趣
- 剑指Offer编程题2——替换空格
剑指Offer编程题2——替换空格 题目描述 请实现一个函数,将一个字符串中的每个空格替换成“%20”.例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happ ...
- 剑指Offer编程题1——二维数组中的查找
剑指Offer编程题1---------------二维数组中的查找 题目描述 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完 ...
- 剑指offer编程题Java实现——面试题12相关题大数的加法、减法、乘法问题的实现
用字符串或者数组表示大数是一种很简单有效的表示方式.在打印1到最大的n为数的问题上采用的是使用数组表示大数的方式.在相关题实现任意两个整数的加法.减法.乘法的实现中,采用字符串对大数进行表示,不过在具 ...
- 剑指offer编程题66道题 36-66
36.两个链表的第一个公共节点 题目描述 输入两个链表,找出它们的第一个公共结点. 1.具有重合节点的两个链表是一个Y字性,用两个堆栈放这两个链表,从尾部开始遍历,直到遍历到最后一个重合节点. 这种算 ...
- 牛客网剑指offer刷题总结
二维数组中的查找: 题目描述:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. 两 ...
- 剑指offer刷题(Tree)
开篇 二刷剑指offer了,本来用Tyora记的笔记,发现字数到四万了就变得好卡o(╥﹏╥)o,刚好开始写博客,就转过来吧,记下来子自己看.不废话,开刷... JZ26. 树的子结构 输入两棵二叉树A ...
- LeetCode剑指Offer刷题总结(一)
LeetCode过程中值得反思的细节 以下题号均指LeetCode剑指offer题库中的题号 本文章将每周定期更新,当内容达到10题左右时将会开下一节. 二维数组越界问题04 public stati ...
- 剑指offer刷题
1.面试题43. 1-n整数中1出现的次数 输入一个整数 n ,求1-n这n个整数的十进制表示中1出现的次数. 例如,输入12,1-12这些整数中包含1 的数字有1.10.11和12,1一共出现了5次 ...
- 剑指offer编程题Java实现——替换空格
题目描述 请实现一个函数,将一个字符串中的空格替换成"%20".例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy. package ...
随机推荐
- php final static const成员属性用法
http://www.111cn.net/phper/php/38976.htm 首先来说说final 1.final不能用来修饰成员属性 2.final只能修饰类和方法 作用:被修饰的类不能被子类所 ...
- 从PC跳转至wap
<script language="JavaScript">function mobile_device_detect(url){var thisOS=navigato ...
- IIS上部署MVC网站,打开后ExtensionlessUrlHandler-Integrated-4.0解决办法
IIS上部署MVC网站,打开后ExtensionlessUrlHandler-Integrated-4.0解决方法 IIS上部署MVC网站,打开后500错误:处理程序“ExtensionlessUrl ...
- IOS学习:在工程中添加百度地图SDK
1.将下载下来的sdk中的inc文件夹.mapapi.bundle.libbaidumapapi.a添加到工程中,其中libbaiduapi.a有两个,一个对应模拟器一个对应真机,导入方法如下: 第一 ...
- [terry笔记]IMPDP报错ORA-39083 Object type TYPE failed to create ORA-02304
今天在使用impdp导入的时候(同一数据库中转换schema),遇到了 ORA-39083: Object type TYPE failed to create with error: ORA-023 ...
- Linux环境下的编译,链接与库的使用
参考博客: http://www.cnblogs.com/qytan36/archive/2010/05/25/1743955.html http://m.blog.csdn.net/article/ ...
- centos php-fpm nginx配置
移除旧的软件包:yum remove httpd* php* 安装:yum install php php-fpm yum install php-gd php-mysql php-mbstring ...
- ubuntu常见错误--Could not get lock /var/lib/dpkg/lock解
通过终端安装程序sudo apt-get install xxx时出错: E: Could not get lock /var/lib/dpkg/lock - open (11: Reso ...
- iOS App Launch Option
iOS 程序启动时总会调用application:didFinishLaunchingWithOptions:,其中第二个参数launchOptions为NSDictionary类型的对象,里面存储有 ...
- Data Developer Center > Learn > Entity Framework > Get Started > Loading Related Entities
Data Developer Center > Learn > Entity Framework > Get Started > Loading Related Entitie ...