首页 > 代码库 > 1007. Maximum Subsequence Sum (25) C#实现

1007. Maximum Subsequence Sum (25) C#实现

代码如下:

 1  public static int F=0,L=0; 2  3         static void Main(string[] args) 4         { 5             int first = 0;//当前取最大值时,对应的第一个数 6             int last = 0;//当前取最大值时,对应的最后一个数 7             int P = 0;//当前最大值 8             int K; 9             int[] N;//存放K个连续的整数10 11             K=Convert.ToInt32(Console.ReadLine());12             N = new int[K];13             string[] str = Console.ReadLine().Split(new Char[]{ });14             for (int i = 0; i < K; i++)15             {16                 N[i] =int.Parse(str[i]);//存值17             }18 19             //先初始化20             P = maxnum(K, 1, N);21             first = F;22             last = L;23 24             for (int i = 2; i <= K; i++)25             {26                 if (maxnum(K,i,N) > P)27                 {28                     P = maxnum(K, i, N);29                     first = F;30                     last = L;31                 }32                 else if (maxnum(K, i, N) == P && first > F)//最大值相同,但是最小索引不同时33                 {34                     P = maxnum(K, i, N);35                     first = F;36                     last = L;37                 }38             }39 40             Console.Write(P+" "+first+" "+last);41             Console.ReadKey();42 43         }44 45         //  求当以group为连续长度时,其最大值46         //  及设置此时最大数最小数值47         public static int maxnum(int K,int group,int[] N)48         {49             int MAX=0;50             int j,i;51             int temp;52             for (i=0; i <= K - group; i++)53             {54                 temp = 0;55 56                 for (j=0; j < group; j++)57                 {58                     temp += N[i + j];59                 }60 61                 if (temp > MAX)62                 {63                     MAX = temp;64                     F = N[i];//设置全局变量65                     L=N[i+j-1];//设置全局变量66                 }67             }68 69             if (MAX < 0&&group==1)//当所有数均为负数时,设置值70             {71                 F = N[0];72                 L = N[K-1];73                 return 0;74             }75             else76                 return MAX;77             78         }

 

1007. Maximum Subsequence Sum (25) C#实现