# 53 Maximum Subarray

給一個任意長度的int array,找出一個總和最大的subarray,回傳該總和。

Concept:

this is a dp problem.
I can create an int array dp, to record the largest sum of each element

Pseudocode:

int[] dp, same length as nums
intialize dp[0] = nums[0]
int max -> save ans
for each element in dp,
    current element = previous element + current element > current element? previous element + current element: cur
    if current element > max, max = current element

return max


Test:
input = [-2,1,-3,4,-1,2,1,-5,4]
dp = [-2, -1, -3, 4, 3, 5, 6, 1, 5]
max = 6

完整程式碼

public class Solution {
    public int maxSubArray(int[] nums) {

        if(nums.length == 0)    return 0;
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int max = dp[0];
        for(int i=1; i<nums.length; i++){
            dp[i] = (dp[i-1] + nums[i]) > nums[i] ? (dp[i-1] + nums[i]) : nums[i];
            if(dp[i] > max) max = dp[i];
        }
        return max;

    }
}

results matching ""

    No results matching ""