zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock——LeetCode

    Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    题目大意:给一个数组,数组的第i个元素是某股票第i天的股价,设计一个算法找出最大的获利。

    解题思路:显然买在前,卖在后,这题n^2的做法估计是AC不了的,动规的方式来做吧,F代表获利函数,那么F[i]=price[i]-price[min],其中min<i,如果price[i]<price[min],那么更新min=i。

    Talk is cheap>>

        public int maxProfit(int[] prices) {
            if (prices == null || prices.length <= 1) {
                return 0;
            }
            int min_pos = 0;
            int profit = Integer.MIN_VALUE;
            for (int i = 0; i < prices.length; i++) {
                int tmp_pro = prices[i] - prices[min_pos];
                if (prices[i] < prices[min_pos]) {
                    min_pos = i;
                }
                profit=Math.max(profit,tmp_pro);
            }
            return profit;
        }
  • 相关阅读:
    spring给容器中注入组件的几种方式
    Linux多进程
    Linux多进程的应用
    Linux进程通信
    Linux信号
    Linux共享内存
    Linux信号量
    Linux多线程
    Linux线程同步
    Linux调用可执行程序
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4405704.html
Copyright © 2011-2022 走看看