zoukankan      html  css  js  c++  java
  • LeetCode "Maximum Subarray"

    Very classic problem. You can brush up your DP and Searching skills.

    DP: 

    class Solution {
    public:
        int maxSubArray(int A[], int n) {
            // dp[i + 1] = max(dp[i] + A[i], A[i]);
            //int start = 0, end = 0;
            int max = A[0];
            int sum = A[0];
            for (int i = 1; i < n; i++)
            {
                if (A[i] >(sum + A[i]))
                {
                    sum = A[i];
                    //if (sum > max) start = i;
                }
                else
                {
                    sum = (sum + A[i]);
                    //if (sum > max) end = i;
                }
                max = sum > max ? sum : max;
            }
            return max;
        }
    };

    Equation: DP[i + 1] = max(DP[i] + A[i + 1], A[i  + 1]). In case subarray location is needed, please check the commented lines.

    And it is brand new to me as a rookie that it can also be solved by binary search ! We get 3 values: result of 1st half, result of 2nd half, and 3rd is the cross boundary case:

    class Solution {
    public:
        int bigger(int a, int b)
        {
            return a > b ? a : b;
        }
        int solve(int A[], int start, int end)
        {
            if (start == end) return A[start];
    
            int mid = start + (end - start) / 2;
            int leftMax = solve(A, start, mid);
            int rightMax = solve(A, mid + 1, end);
            //    cross boundary?
            int sum0 = A[mid],    cMaxL = A[mid];
            for (int i = mid - 1; i >= start; i--)
            {
                sum0 += A[i];
                cMaxL = bigger(sum0, cMaxL);
            }
            int sum1 = A[mid + 1], cMaxR = A[mid + 1];
            for (int i = mid + 2; i <= end; i++)
            {
                sum1 += A[i];
                cMaxR = bigger(sum1, cMaxR);
            }
            return bigger(bigger(leftMax, rightMax), cMaxL + cMaxR);
        }
    
        int maxSubArray(int A[], int n) {
            return solve(A, 0, n-1);
        }
    };

    Deserve to revise later !

  • 相关阅读:
    maven scope取值
    HashMap 解析
    MySQL中int(M)和tinyint(M)数值类型中M值的意义
    PyCharm 快捷键
    js 闭包,原型链,作用域链
    阿拉伯数字转中文大写金额JS(JavaScript方法)
    JSch
    Java面试点 -【笔记】
    tomcat Connector配置项 参数优化说明
    QRCanvas 示例使用
  • 原文地址:https://www.cnblogs.com/tonix/p/3857651.html
Copyright © 2011-2022 走看看