排除不合理的项(负值), 设定一个标杆sum, 往后扫描看是否有比sum好的情况.

We should ensure the following conditions:

  1. The result must be the max sum.

  2.* If more than one sum is max(same max value), choose the longer sequence.

  3.* If more than one sum is max & same length, choose the former sequence.

#!/usr/bin/python2.7
#File: maxChildSum.py
#Author: lxw
#Time: 2014-08-22
#Usage: Find the max sum of a sub-sequence in a sequence.
#NOTE: @1: first, must be the max sum.
# @2: if more than one sum is max(same max value), choose the longer sequence. def main():
#arr = [-12, 0, -14, -14, -13, -14, -2] #"zero" test.
#arr = [0, -14, -14, -13, -14, -2] #another "zero" test.
arr = [-100, -14, -14, -13, -14, -2] #"all negtive" test.
#arr = [-12, 10, 2, -14, -14, 13, -2] #"longer sequence but not equal sum" test.
#arr = [-12, 0, 10, -14, -14, -2] #"as long as better" test.
#arr = [-12, 0, 10, -14, -14, 3, 7, -2] #"same sum & same length" test.
#arr = [-12, 10, -14, -14, 3, 7, -2] #"same sum but longer sequence" test. index = 0
length = len(arr)
while arr[index] < 0:
index += 1
if index == length:
break if index < length:
sum = -1 #This initial value is important.
start = index
temp_sum = 0 #sum
temp_start = index
end = 0 while index < length:
temp_sum += arr[index]
if temp_sum >= 0:
if temp_sum > sum:
sum = temp_sum
start = temp_start
end = index
elif temp_sum == sum:
if start == temp_start:
end = index
elif index - temp_start > end - start:
start = temp_start
end = index
else:
temp_sum = 0
temp_start = index + 1
index += 1
print "max sum:{0:<4}start:{1:<4}end:{2:<4}max length:{3:<4}".format(sum, start, end, end-start+1)
else:
#All the numbers are negative.
print "max sum:{0:<4}start:{1:<4}end:{2:<4}max length:{3:<4}".format(0, 0, 0, 0) if __name__ == '__main__':
main()
else:
print "Being imported as a module."

最新文章

  1. iOS 组件化方案探索
  2. Android--将图片存放到我们本地
  3. pow(x,y):返回x的y次幂
  4. eclipse 导入Android项目时报告 Invalid Project Description
  5. 线程、线程句柄、线程ID
  6. poj 3253 Fence Repair(模拟huffman树 + 优先队列)
  7. Android studio之更改快捷键及自动导包
  8. 自定义的Server
  9. URL特殊字符需转义
  10. nginx四层负载均衡配置
  11. Kaggle实战之二分类问题
  12. html 微信video放大后无法返回问题
  13. C#中Dictionary的介绍
  14. python使用正则解析网络地址的各个部分
  15. 【登录异常解决】Ubuntu 输入正确的密码后重新返回到登陆界面
  16. pyqt---------事件与信号处理
  17. 流媒体技术学习笔记之(二)RTMP和HLS分发服务器nginx.conmf配置文件(解决了,只能播放RTMP流而不能够播放HLS流的原因)
  18. html (第四本书第八章参考)
  19. WordPress 建站教程:新手搭建 WordPress个人博客图文教程(完全版)
  20. PHP算法之排序算法(PHP内置排序函数)

热门文章

  1. C# Post Json数据到对方url
  2. mysql创建数据库时设置编码方式
  3. linux学习之缓存机制
  4. Python内置函数之bool()
  5. c++ what happens when a constructor throws an exception and leaves the object in an inconsistent state?
  6. apache POI 操作excel&lt;导入导出&gt;
  7. ssh加密访问
  8. Spell checker - poj 1035 (hash)
  9. important——》sql server 2000安装图解
  10. WPF绑定Binding及模式