LeetCode小算法记录(九)

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package leetCodeTest;

public class 买卖股票的最佳时机 {

    public static void main(String[] args) {
        int prices[] = {7,1,5,3,6,4};
        final int i = maxProfit(prices);
        System.out.println("i = " + i);
    }

    /**
     * 传统方法使用双循环嵌套查询。
     * 因为需要找到当前位置与之前位置的差的最小值,所以使用双循环即可找到最佳答案。
     * @param prices
     * @return
     */
//    public static int maxProfit(int[] prices) {
//        int i,j;
//        int temp = 0;
//        int te;
//        for (i = 0;i<prices.length;i++){
//            for (j = 0;j<i;j++){
//                te = prices[i] - prices[j];
//                if (te > temp){
//                    temp = te;
//                }
//            }
//        }
//        int result = temp;
//        return result;
//    }

    /**
     * 升级版方法,单循环查找。
     * 因为只需要知道差值的大小即可,所以只需要用当前位置的值减去之前位置的最小值就可以找到最佳答案
     * @param prices
     * @return
     */
    public static int maxProfit(int[] prices) {
        int i;
        int min = 0;
        int temp = 0;
        int inmin = Integer.MIN_VALUE;
        for (i = 0;i<prices.length;i++){
            if(prices[i] < min && inmin < i){
                min = prices[i];
                inmin = i;
            }
            if (prices[i] - min > temp)
                temp = prices[i] - min;
        }
        return temp;
    }
}
发布了100 篇原创文章 · 获赞 12 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_31404603/article/details/104749931
今日推荐