연속 최대화
가장 쉽게 떠오르는 것은 빈거법과 분리법이다.나중에 인터넷에서 검색해 보니 동적 기획으로 이 문제를 해결하는 것이 매우 우아했다. 다음은 동적 기획법으로 이 문제를 해결하는 코드이다.
/**
* ,
*
* @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);
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.