算法的重要性,我就不多說了吧,想去大廠,就必須要經(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.
private int max = Integer.MIN_VALUE;
public int maxSubArray(int[] nums) {
int sum;
for (int i = 0; i < nums.length; i++) {// 子序列左端點
for (int j = i; j < nums.length; j++) {// 子序列右端點
sum = 0;
for (int k = i; k <= j; k++) {//暴力計算
sum += nums[k];
}
if (sum > max) {
max = sum;
}
}
}
return max;
}
class Solution {
public int maxSubArray(int[] nums) {// 動態(tài)規(guī)劃法
int sum=nums[0];
int n=nums[0];
for(int i=1;i<nums.length;i++) {
if(n>0)n+=nums[i];
else n=nums[i];
if(sum<n)sum=n;
}
return sum;
}
}
上期推文:
聯(lián)系客服