GeekVan

导航

最大子数组问题(动态规划求解)

最大子数组问题代码:

 1 #include<iostream>
 2 using namespace std;
 3 #define MAX 100//define the max large of the array
 4 
 5 int arr[MAX];
 6 
 7 void devide(int size)//动态规划求解最大子数组问题
 8 {
 9     int a[MAX]={0};
10     for(int i=0;i<size-1;i++)
11     {
12         a[i]=arr[i+1]-arr[i];//求相邻的两个数的差值
13         
14     }//a from 0 to size-2
15     int sum[MAX]={0};
16     sum[0]=a[0];//initial
17     int low=0,high=0;//intital
18     int t=0;
19     for(i=0;i<size-1;i++)
20     {
21         t=i+1;
22     if(a[i]>0)
23     {
24         int count =0;
25         int j;int k;int total=0;int m;int large=0;int lowi;
26         for(j=high+1;j<=i;j++)
27         {
28             count=count+a[j];
29         }
30         for(k=high+1;k<=i;k++)//search the low location
31         {
32             total=0;
33           for(m=i;m>=k;m--)
34           {
35               total=total+a[m];
36           }
37           if(total>large)
38           {
39               large=total;
40               lowi=k;
41               
42           }
43 
44         }
45         if(count+sum[t-1]>large&&count>0)
46         {
47             sum[t]=sum[t-1]+count;
48             high=i;
49         }
50         else if(sum[t-1]>large)
51         {
52             sum[t]=sum[t-1];
53         }
54         else
55         {
56             sum[t]=large;
57             low=lowi;
58             high=i;
59         }
60     }
61     else
62     {
63         sum[t]=sum[t-1];    
64     }
65 
66     }
67     cout<<"low="<<low<<" ";
68     cout<<"high="<<high<<" ";
69     cout<<sum[t]<<endl;
70 
71 }
72 int main()
73 {
74     int size;
75     cout<<"Input the size of the array:";
76     cin>>size;
77     cout<<"Input the data of the array:";
78     for(int i=0;i<size;i++)
79         cin>>arr[i];
80      devide(size);
81     return 0;
82 }

运行结果:

 

posted on 2017-01-18 14:25  GeekVan  阅读(223)  评论(0编辑  收藏  举报