?LeetCode刷題實(shí)戰(zhàn)53:最大子序和
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?最大子序和,我們先來看題面:
https://leetcode-cn.com/problems/maximum-subarray/
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
題意
樣例
輸入: [-2,1,-3,4,-1,2,1,-5,4]
輸出: 6
解釋: 連續(xù)子數(shù)組 [4,-1,2,1]?的和最大,為 6。
解題
private?int?max = Integer.MIN_VALUE;
????public?int?maxSubArray(int[] nums)?{
????????int?sum;
????????for?(int?i = 0; i < nums.length; i++) {// 子序列左端點(diǎn)
????????????for?(int?j = i; j < nums.length; j++) {// 子序列右端點(diǎn)
????????????????sum = 0;
????????????????for?(int?k = i; k <= j; k++) {//暴力計算
????????????????????sum += nums[k];
????????????????}
????????????????if?(sum > max) {
????????????????????max = sum;
????????????????}
????????????}
????????}
????????return?max;
????}
2、動態(tài)規(guī)劃解法:
class?Solution?{
????public?int?maxSubArray(int[] nums)?{// 動態(tài)規(guī)劃法
????????int?sum=nums[0];
????????int?n=nums[0];
????????for(int?i=1;i????????????if(n>0)n+=nums[i];
????????????else?n=nums[i];
????????????if(sum????????}
????????return?sum;
????}
}
上期推文:
