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

    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.

    会时间超时的一种解法,最差的时间复杂度位O(n*n)

    public class Solution {
        public int maxProfit(int[] prices) {
            if(prices.length==0||prices.length==1)
                return 0;
            int max=0;
            boolean bo=true;
            for(int n=1;n<prices.length;n++){
                if(prices[n]>prices[n-1])
                    bo = false;
            }
            if(bo)
                return 0;
            for(int i=0;i<prices.length-1;i++){
                int temp = FindMax(prices,i);
                if(temp!=prices[i]){
                    int t = temp-prices[i];
                    if(t>max)
                        max=t;
                }
            }
            return max;
        }
    
        private int FindMax(int[] prices, int i) {
            // TODO Auto-generated method stub
            int max = prices[i];
            for(int j=i+1;j<prices.length;j++){
                if(prices[j]>max)
                    max = prices[j];
            }
            return max;
        }
    }

    另外一种优化的accept的解法

    public class Solution {
        public int maxProfit(int[] prices) {
            if(prices.length==0||prices.length==1)
                return 0;
            int max = prices[prices.length-1];
            int re = 0;
            for(int i=prices.length-2;i>=0;i--){
                int temp = max-prices[i];
                if(temp>re)
                    re = temp;
                if(prices[i]>max)
                    max=prices[i];
            }
            return re;
        }
    }
  • 相关阅读:
    C# 轻松读取、改变文件的创建、修改、访问时间 z
    C#中将dll汇入exe z
    ASP.NET中引用dll“找不到指定模块"的完美解决办法 z
    C# 调用第三方DLL z
    [ACM_贪心] Radar Installation
    Beauty Contest
    [ACM_几何] Wall
    [ACM_几何] Pipe
    [ACM_几何] Fishnet
    [ACM_动态规划] 找零种类
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3718331.html
Copyright © 2011-2022 走看看