zoukankan      html  css  js  c++  java
  • [LintCode笔记了解一下]41.Maximum Subarray

    Given an array of integers, find a contiguous subarray which has the largest sum.

    首先

    當題目涉及到求最大最小值時,最初的比較數字就應當設置爲INT_MAX或INT_MIN,更爲安全。
    
    <limits.h>中有INT_MAX和INT_MIN的宏定義可直接使用。
    
    或者自行定義宏
    
    #define INT_MAX 0x7fffffff
    
    #define INT_MIN 0x80000000
    
    INT_MAX = 2147483647
    
    INT_MIN = -2147483648

    然后

    思路一:
    进行两次循环,遍历所有可能的情况,找到最大的子数组,时间复杂度为O(n^2); 
    思路二:
    对于任意一个子数组和,如果大于0,那么它再添加一个数,他的贡献是正值,如果子数组和小于0,再添加一个数,它的贡献则为负值,这时候不如将当前子数组舍掉,新数成为一个新数组。(动态规划Dynamic Programming)

    思路一

    public int maxSubArray(int[] nums) {
            // write your code
            if (nums.length == 1) return nums[0]; 
            int max = nums[0];
            for (int i = 0; i < nums.length; i++){
                int temp = nums[i];
                for (int j = i+1; j < nums.length; j++){
    
                    temp += nums[j];
                    if (temp > max){
                        max = temp;
                    }
                }
            }
    
            return max;
        }

    思路二

    public int maxSubArray(int[] nums) {
            // write your code
            int max = Integer.MIN_VALUE;
            int sum = Integer.MIN_VALUE;
            for (int i = 0; i < nums.length; i++){
                sum = sum<0 ? nums[i] : nums[i]+sum;
                if (sum>max){
                    max = sum;
                }
            }
    
            return max;
        }
  • 相关阅读:
    JS在火狐浏览器下如何关闭标签?
    .NET3.5项目转.NET2.0项目技巧
    GCHandler的使用
    多类选择器
    线程的Abort方法有感
    多线程死锁
    mysql 查看数据库、表的基本命令
    PHP往mysql数据库中写入中文失败
    TLS / SSL密码强化的建议
    MongoDB在Linux下常用优化设置
  • 原文地址:https://www.cnblogs.com/otakuhan/p/8606841.html
Copyright © 2011-2022 走看看