0
0

More than 1 year has passed since last update.

53 解答

Last updated at Posted at 2022-05-09

Memoizationを使った解法

public int maxSubArray(int[] nums) {
	    int ans = nums[0];
	    int[] sumArray =  new int[nums.length];
	    sumArray[0] = nums[0];
	 
	    for(int i=1; i<nums.length; i++){
	        sumArray[i] = Math.max(nums[i], sumArray[i-1] + nums[i]);
	        ans = Math.max(ans, sumArray[i]);
	    }
	 
	    return ans;
	}

別解

public int maxSubArray(int nums[]) {

		int size = nums.length;
		int ans = Integer.MIN_VALUE;
		int tempSubArraySum = 0;

		for (int i = 0; i < size; i++) {
			tempSubArraySum += nums[i];

			if (ans < tempSubArraySum) {
				ans = tempSubArraySum;

			}

			if (tempSubArraySum < 0) {
				tempSubArraySum = 0;

			}
		}
		return ans;

	}

ここがよくわからなかった↓

if (tempSubArraySum < 0) {
				tempSubArraySum = 0;
}

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0