第28章:最大连续乘积子串

-2.5 4 0 3 0.5 8 -1Ans:(3,0.5,8)

template<typenameComparable>

Comparable maxprod(constvector<Comparable>& v)

{

 int i;

 Comparable maxProduct =1;

 Comparable minProduct =1;

 Comparable maxCurrent = 1;

 Comparable minCurrent =1;

 

 for(inti=0;i<v.size();i++)

 {

  maxCurrent *= v[i];

  minCurrent *= v[i];

  if(maxCurrent >maxProduct)

   maxProduct =maxCurrent;

  if(minCurrent >maxProduct)

   maxProduct =minCurrent;

  if(maxCurrent <minProduct)

   minProduct =maxCurrent;

  if(minCurrent <minProduct)

   minProduce =minCurrent;

  if(minCurrent >maxCurrent)

  Swap(maxCurrent,minCurrent);

  if(maxCurrent < 1)

   maxCurrent = 1;

  return maxProduct;

 }

}

 

 

*直接用动态规划求解

状态转移方程:max表示以a结尾的最大连续子串

Max = max{a,Max[i-1]*a,Min[i-1]*a};

Min =min{a,Max[i-1]*a,Min[i-1]*a};

 

C++代码:

double func(double* a ,constint n)

{

 double* maxA = newdouble[n];

 double* minA = newdouble[n];

 msxA[0] = min[A] = a[0];

 double value = maxA[0];

 for(int i=1;i<n;i++)

 {

  maxA[i] =max(max(a[i],maxA[i-1]*a[i]),minA[i-1]*a[i]);

  minA[i] =min(,min(a[i],maxA[i-1]*a[i]),minA[i-1]*a[i]);

  vlaue =max(value,maxA[i]);

 }

 delete [] maxA;

 delete [] minA;

 return value;

}

posted @ 2015-09-26 23:12  Uncle_Nucky  阅读(147)  评论(0编辑  收藏  举报