An old question in programming: An array that finds continuous subsequences to maximize the sum. We can use the linear scanning algorithm to solve this problem. After this problem is transformed, it becomes: finding continuous subsequences so that they are closest to a certain number. The original time complexity is linear. We can accumulate an array, sort it, and calculate the adjacent difference. The number closest to k is what we want. The Code is as follows:
- IntApproximate (Int* PArry,IntLen)
- {
- Int* Cum = 0;
- Int* Realarry =New Int[Len + 1];
- Realarry [0] = 0;
- Cum = realarry + 1; // cum [-1] = 0
-
- // Accumulate and store the sum of pArry [0... I] In cum [I]
- For(IntI = 0; I <len; I ++)
- {
- Cum [I] = cum [I-1] + pArry [I];
- }
- Sort (cum, cum + len); // sorts cum
- IntIMin = cum [1]-cum [0];
- For(IntK = 1; k <len; k ++)
- {
- IMin = min (iMin, cum [k]-cum [k-1]); // returns the smallest difference between two adjacent elements.
- }
- ReturnIMin;
- }