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;
        }
    }
  • 相关阅读:
    神兽保佑-代码无BUG
    HDU 1022 Train Problem I (数据结构 —— 栈)
    iOS开发
    漫谈程序猿系列:无BUG不生活
    王立平--Unity破解
    java远程调用rmi入门实例
    高仿美团iOS版,版本5.7
    JAVA日志系统
    读《互联网创业password》之随想
    解决iOS空指针数据的问题
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3718331.html
Copyright © 2011-2022 走看看