zoukankan      html  css  js  c++  java
  • 软件工程概论-课后作业4(子数组成环求最大值)

    [设计思路]

        在之前(子数组求最大值)的基础之上,要使成环后的数组求取其最大子数组之和,需要确定遍历循环开始的位置和其结束的位置。

        1.使用一个for循环,遍历至最后一个数。当某个数之前的子数组为负值(即子数组最大值要从当前数来计时),添加一个标记,作为下一个for循环停止的位置。

        2.再使用一个for循环,遍历至标记所在处。

    [程序代码]

    import java.util.*;
    
    public class MaxsArray 
    {
        public static void main(String args[])
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入你要求子数组最大值的数组长度:");
            int length = sc.nextInt();
            int array[] = new int[length];
            
            System.out.println("请输入你要求子数组最大值的数组的数:");
            for(int i=0;i<length;i++)
            {
                array[i] = sc.nextInt();
            }
            
            int max = array[0];
            int tempmax = array[0];
            int temp=0;
            
            for(int i=1;i<length;i++)
            {
                if(tempmax<0)
                {
                    tempmax = array[i];
                    temp=i-1;
                }
                else
                {
                    tempmax+=array[i];
                }
                if(tempmax>max)
                {
                    max = tempmax;
                }
            }
            for(int i=0;i<=temp;i++)
            {
                if(tempmax<0)
                {
                    tempmax = array[i];
                }
                else
                {
                    tempmax+=array[i];
                }
                if(tempmax>max)
                {
                    max = tempmax;
                }
            }
            System.out.println("子数组的最大值为:"+max);
        }
    }

    [结果截图]

    [总结]

        一个程序的设计思路对一个程序的实现远重于所花费在敲代码上的功夫,所以,在编写一个程序之前,一定要好好构建设计思路,只有思路清晰了才能快速的实现自己的程序。

  • 相关阅读:
    XCode下Swift – WebView IOS demo
    swift-初探webView与JS交互
    Swift 实践之UIWebView
    iOS 权限判断 跳转对应设置界面
    iOS~判断应用是否有定位权限
    iOS 判断是否有权限访问相机,相册
    UIAlertController中TextField的用法
    Swift-UITextField用法
    多年iOS开发经验总结(一)
    Python lambda和reduce函数
  • 原文地址:https://www.cnblogs.com/Againzg/p/5395995.html
Copyright © 2011-2022 走看看