MAXIMUM SUBSEQUENCE SUM PROBLEM
2024-08-26 01:06:29
排除不合理的项(负值), 设定一个标杆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."
最新文章
- iOS 组件化方案探索
- Android--将图片存放到我们本地
- pow(x,y):返回x的y次幂
- eclipse 导入Android项目时报告 Invalid Project Description
- 线程、线程句柄、线程ID
- poj 3253 Fence Repair(模拟huffman树 + 优先队列)
- Android studio之更改快捷键及自动导包
- 自定义的Server
- URL特殊字符需转义
- nginx四层负载均衡配置
- Kaggle实战之二分类问题
- html 微信video放大后无法返回问题
- C#中Dictionary的介绍
- python使用正则解析网络地址的各个部分
- 【登录异常解决】Ubuntu 输入正确的密码后重新返回到登陆界面
- pyqt---------事件与信号处理
- 流媒体技术学习笔记之(二)RTMP和HLS分发服务器nginx.conmf配置文件(解决了,只能播放RTMP流而不能够播放HLS流的原因)
- html (第四本书第八章参考)
- WordPress 建站教程:新手搭建 WordPress个人博客图文教程(完全版)
- PHP算法之排序算法(PHP内置排序函数)
热门文章
- C# Post Json数据到对方url
- mysql创建数据库时设置编码方式
- linux学习之缓存机制
- Python内置函数之bool()
- c++ what happens when a constructor throws an exception and leaves the object in an inconsistent state?
- apache POI 操作excel<;导入导出>;
- ssh加密访问
- Spell checker - poj 1035 (hash)
- important——》sql server 2000安装图解
- WPF绑定Binding及模式