上篇用有限状态机来求解,其实也是进行了一遍扫描,只是我把问题考虑的复杂了。
对于扫描,我觉得首先要问自己3个问题:
1. 如何扫描 (这里是遍历数组元素)
2. 每次扫描会改变什么 (这里的算法会改变maxendinghere,前一篇的算法是改变状态)
3. 改变的东西会对结果有影响么 (maxendinghere如果大于maxsofar,那么maxsofar就被赋值为maxendinghere)
不同的考虑问题的方式引入不同的解决方案,其中的差距太大了!!前一篇我太关注正负号了,导致我采用了序列分段,状态转移的方式去解决问题;这里的解法关注最大和,以及有可能影响最大和的因素,maxsofar和maxendinghere的相对大小。虽然时间复杂度都是O(n),但是,高下立现!
代码如下(python):
#!/usr/bin/python
def scan(vector): # return (maxsofar, low, high)
length = len(vector)
maxsofar = 0
maxendinghere = 0
low = 0
high = 0
low2 = 0
high2 = 0
for i in range(0, length):
if maxendinghere + vector[i] > 0:
maxendinghere = maxendinghere + vector[i]
high2 = i+1
else:
maxendinghere = 0
low2 = i+1
if maxsofar >= maxendinghere:
high = high
low = low
maxsofar = maxsofar
else:
high = high2
low = low2
maxsofar = maxendinghere
return (maxsofar, low, high)
def test():
vector = [-1, -1, -1, -1]
(maxsofar, low, high) = scan(vector)
print vector
print maxsofar, low, high
print
vector = [1, -1, -1, -1]
(maxsofar, low, high) = scan(vector)
print vector
print maxsofar, low, high
print
vector = [-1, -1, -1, 1]
(maxsofar, low, high) = scan(vector)
print vector
print maxsofar, low, high
print
vector = [-1, 2, 3, -4]
(maxsofar, low, high) = scan(vector)
print vector
print maxsofar, low, high
print
vector = [1, 2, 3, 4]
(maxsofar, low, high) = scan(vector)
print vector
print maxsofar, low, high
print
vector = [31, -41, 59, 26, -53, 58, 97, -93, -23, 84]
(maxsofar, low, high) = scan(vector)
print vector
print maxsofar, low, high
print
def main():
test()
if __name__ == '__main__':
main()
运行结果:
root@localhost :/home/James/mypro/Python# ./scan.py
[-1, -1, -1, -1]
0 0 0
[1, -1, -1, -1]
1 0 1
[-1, -1, -1, 1]
1 3 4
[-1, 2, 3, -4]
5 1 3
[1, 2, 3, 4]
10 0 4
[31, -41, 59, 26, -53, 58, 97, -93, -23, 84]
187 2 7
root@localhost :/home/James/mypro/Python#
后记:感觉python真的很适合写这种小demo,又快又方便。