• 求连续的子数组的最大和


     //求子数组的最大和
            public static int maxSubarray(int[] a, int size)
            {
                if (size <= 0) Console.WriteLine("error array size");
                int sum = 0;
                int max = 0;
                int cur = 0;
                while (cur < size)
                {
                    sum += a[cur++];
                    if (sum > max)
                    {
                        max = sum;
                    }
                    else if (sum < 0)
                    {
                        sum = 0;
                    }
                }
                return max;

            }

            //求子数组的最大和
            static int Max(int[] array, int size)
            {
                int curSum = 0;
                int maxSum = 0;
                for (int i = 0; i < size; i++)
                {
                    curSum += array[i];
                    if (curSum < 0) curSum = 0;
                    if (curSum > maxSum) maxSum = curSum;

                }
                if (maxSum == 0)
                {            //若是数组中的元素均为负数,则输出里面的最大元素
                    maxSum = array[0];          //当然这步也可以写到上面一个循环里
                    for (int i = 1; i < size; i++)
                    {
                        if (maxSum < array[i]) maxSum = array[i];
                    }
                }
                return maxSum;
            }

  • 相关阅读:
    22、栈的应用-中缀表达式转后缀表达式
    21、栈的应用-就近匹配
    20、双向链表
    19、链式栈
    Eclipse 重新加载插件
    Asp.net web form 使用IOC(Unity) 构造函数注入Page,.net Framework 4.7.2
    asp.net webform 多语言
    sql server 生成数字辅助表
    查询指定数据库的慢语句
    2008 sql 揭秘 第4章的数据库脚本
  • 原文地址:https://www.cnblogs.com/dasydong/p/3280966.html
Copyright © 2020-2023  润新知