1, divide and conquer thought
Calculates the maximum and of any successive sub-vectors in the input vector.
[31,-41,59,26,-53,58,97,-93,-23,84]
Direct algorithm:
[CPP]View Plaincopy
- Maxsofar=0
- For i = [0,n]
- sum = 0
- for j = [I, n]
- Sum + = X[j]
- Maxsofar=max (Maxsofar,sum)
Divide and conquer thought:
The vector is decomposed into two sub-vectors, solving the maximum and maximum of each vector, or the maximal value at the boundary of the child vector A and the sub-vector b
[CPP]View Plaincopy
- Float maxsum3 (l,u)
- if (L > U)
- return 0
- if (L = = u)
- return Max (0,x[1])
- m = (l + u)/2
- Lmax = SUM = 0
- For (i = m; i>=l;i--)
- Sum + = X[i]
- Lmax=max (Lmax,sum)
- Rmax=sum=0
- for i = (M,u]
- Sum+=x[i]
- Rmax=max (Rmax,sum)
- return Max (LMAX+RMAX,MAXSUM3 (l,m), maxsum3 (m+1,u))
The initial call is as follows: Answer=maxsum3 (0,n-1)
Decompose n vectors into n-1 and vector n
[CPP]View Plaincopy
- Maxsofar=0
- Maxendinghere=0
- For i = [0,n]
- Maxendinghere=max (maxendinghere+x[i],0)
- Maxsofar=max (Maxendinghere,maxsofar)
[Data structure] some common algorithm ideas