연속 최대화

1579 단어
수조에서 연속 구간의 크기와 최대를 구하고, 이 구간의 하표를 인쇄합니다.
가장 쉽게 떠오르는 것은 빈거법과 분리법이다.나중에 인터넷에서 검색해 보니 동적 기획으로 이 문제를 해결하는 것이 매우 우아했다. 다음은 동적 기획법으로 이 문제를 해결하는 코드이다.

/**
	 *        ,     
	 * 
	 * @param a
	 */
	public static void maxSubSequence(int[] a) {
		int curSum = 0;
		int maxSum = a[0];
		int start = 0, end = 0;
		int tempStart = 0;
		for (int i = 0; i < a.length; i++) {
			if (curSum == 0)
				tempStart = i;

			curSum += a[i];
			if (curSum > maxSum) {
				maxSum = curSum;
				end = i;
				start = maxSum < 0 ? end : tempStart;
			}

			if (curSum < 0)
				curSum = 0;

		}
		System.out.println("maxSum:" + maxSum + "\tstart:" + start + "\tend:"
				+ end);
	}

	public static double random(int start, int end) {
		return Math.ceil(Math.random() * (end - start) + start);
	}

	public static void main(String[] args) {
		int[] a = { 90, 9, 0, -7, 29, 7, -99, -72, 40, 63, 96, -92, 25, -53,
				-49, -6, -7, -37, 29, 39 };
		int[] b = { -3, -3, -1, -4, -7, -3, -1, -5 };
		maxSubSequence(a);
		maxSubSequence(b);

		// int start = -100;
		// int end = 100;
		// int[] arr = new int[20];
		// for (int i = 0; i < arr.length; i++) {
		// arr[i] = (int) random(start, end);
		// }
		// System.out.println(ArrayUtils.toString(arr));
		// maxSubSequence(arr);
	}

좋은 웹페이지 즐겨찾기