Problem
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
ExampleFor example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Solutionclass Solution { public int maxSubArray(int[] nums) { if (nums == null || nums.length == 0) return 0; int max = nums[0], sum = max; for (int i = 1; i < nums.length; i++) { if (sum < 0) { sum = nums[i]; } else { sum += nums[i]; } max = Math.max(max, sum); } return max; } }
class Solution { public int maxSubArray(int[] nums) { int sum = nums[0], n = nums.length; int[] dp = new int[n]; dp[0] = sum; for (int i = 1; i < n; i++) { if (sum < 0) sum = nums[i]; else sum += nums[i]; dp[i] = Math.max(dp[i-1], sum); } return dp[n-1]; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/68243.html
摘要:復雜度思路要保留一個到某一位來看的最大值和最小值。因為在數組中有負數的出現,所以到這一位為止的能得到的最大值,可能是由之前的最大值和這個數相乘得到,也可能是最小值和這個數相乘得到的。 Leetcode[152] Maximum Product Subarray Find the contiguous subarray within an array (containing at le...
Problem Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isnt one, return 0 instead. Note The sum of the entire nums array is guaranteed to fit ...
摘要:最新更新請見原題鏈接動態規劃復雜度時間空間思路這是一道非常典型的動態規劃題,為了求整個字符串最大的子序列和,我們將先求較小的字符串的最大子序列和。而最大子序列和的算法和上個解法還是一樣的。 Maximum Subarray 最新更新請見:https://yanjia.me/zh/2019/02/... Find the contiguous subarray within an ar...
摘要:題目詳情輸入一個數組和一個整數。要求找出輸入數組中長度為的子數組,并且要求子數組元素的加和平均值最大。 題目詳情 Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need ...
摘要:題目要求從一個整數數組中找到一個子數組,該子數組中的所有元素的乘積最大。比如數組的最大乘積子數組為思路與代碼這題目考察了動態編程的思想。至于為什么還要比較,是因為如果是一個負數的,那么之前的最小乘積在這里可能就成為了最大的乘積了。 題目要求 Find the contiguous subarray within an array (containing at least one num...
摘要:這是一道簡單的動規題目,同步更新數組解決了為負數的問題。即使是求最小乘積子序列,也可以通過取和的最小值獲得。 Problem Find the contiguous subarray within an array (containing at least one number) which has the largest product. Example For example, g...
閱讀 3189·2023-04-26 03:06
閱讀 3689·2021-11-22 09:34
閱讀 1134·2021-10-08 10:05
閱讀 3024·2021-09-22 15:53
閱讀 3530·2021-09-14 18:05
閱讀 1387·2021-08-05 09:56
閱讀 1880·2019-08-30 15:56
閱讀 2124·2019-08-29 11:02