Java algorithm essay (1)

Keywords: Java

1. Maximum subsequences and problems

Given (possibly negative) integers a(1), a(2) a(n), find a(1)+a(2) + +The maximum value of a(j).

That is to say: in a series of integers, find several consecutive integers, and the sum of these integers is the largest. For reference. https://www.cnblogs.com/hapjin/p/5404705.html)

 

 

 

(1) Time complexity O(nLogn) space complexity O(n2)
dp[0][2] represents the maximum sum of steps in [0] position [2]
dp[i][0] represents the maximum sum of [0] positions
Since there are (arr.length - i) steps to the end of the array at most, and then it will cross the boundary, so go straight from i to the end

 

static int OnLogn(int []arr){
	int n = arr.length;
	int maxSum = arr[0];
	int[][] dp = new int[n][n + 1];

	for (int i = 0; i < n; i++) {
		for (int j = i+1; j < n + 1 && arr[i] > 0; j++) {
			dp[i][j - i] = dp[i][j -i- 1] + arr[j - 1];
			maxSum = max(maxSum, dp[i][j - i]);
		}
	}
	return maxSum;
}

 

(2) Time complexity O(nLogn) space complexity O(n)
The main improvement of (1) is to use rolling array
(lines 8-9 do not modify I, so lines 8-9 are changed to DP [J-I] = DP [j-i-1] + arr [J-1]; this can reduce space complexity.)

 

static int OnLogn(int []arr){
	int n = arr.length;
	int maxSum = arr[0];
	int[] dp = new int[n + 1];
	/*
	 * dp[0][1] Represents the maximum value of one step of 0 coordinate
	 */

	for (int i = 0; i < n; i++) {
		for (int j = i+1; j < n + 1 && arr[i] > 0; j++) {
			dp[j - i] = dp[j -i- 1] + arr[j - 1];
			maxSum = max(maxSum, dp[j - i]);
		}
	}
	return maxSum;
}

  

 

(2) time complexity O(n) space complexity O(n)

static int On(int[] arr) {
        int maxSum = arr[0];
        int thisSum = arr[0];
        for (int i = 0; i < arr.length; i++) {
            thisSum += arr[i];
            if (thisSum > maxSum)// No processing is required when thisSum is between [0,maxSum]
                maxSum = thisSum;
            else if (thisSum < 0)// Note: if the current element makes the subsequence negative, discard the subsequence (equivalent to 0 for this sum), starting from the next round of for
                thisSum = 0;
            System.out.println(i + " : "+thisSum);
        }
        if(maxSum < 0)
	        for(int i = 0; i < arr.length; i++)
	        	if(arr[i] > maxSum) maxSum = arr[i];
        return maxSum;
    }

Posted by jeicrash on Mon, 06 Jan 2020 17:11:16 -0800