问题:
Given array of integers representing historic stock prices. Find the buying and selling points to maximize the profit.
给你一个整数数组,数组的值代表股票的历史价格。找到买点和卖点,使得利润最大。假设数组为array = {3, 8, 1, 2, 19, 22, 2, 35, 23},那么买点价格是 1, 卖出价格是 35。
分析:
因为买了以后,我们只能在买点后面寻找卖点。也就是说,如果买点的位置是 array[i], 卖点的位置是 array[j], 那么要求 j > i。
方法1:如果要使得利润最大,我们可以对每个点和其后面的点作比较,找到最大(array[j] - array[i])。因为i 的范围是 0 到 n - 1 (假设数组长度为 n), 而 j 的范围是 i + 1 到 n - 1, 所以,算法复杂度为 O(N^2)。