zoukankan      html  css  js  c++  java
  • Best-time-to-buy and-sell-stock

    (解二最优,我现在能写的最好的了) 

    题目:

    Say you have an array for which the i th 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

     解一:

    public class Solution {
        public int maxProfit(int[] prices) {
            int max = 0, temp = 0 , i = 0 , j = 0;
            for(i = 0; i < prices.length-1; i++){
                for(j = i; j < prices.length-1 ; j++){
                    temp = prices[j+1] - prices[i];
                    if(temp>max){
                        max = temp; 
                    }
                }
            }
            return max;
        }
    }
    

      

    解二:

      

    public class Solution {
        public int maxProfit(int[] prices) {
            int max = 0 , i = 0 , j = 0;
            for(i = 0; i < prices.length-1; i++){
                for(j = i; j < prices.length-1 ; j++){
                    if(prices[j+1] - prices[i]>max){
                        max = prices[j+1] - prices[i]; 
                    }
                }
            }
            return max;
        }
    }
    

      

    解三:

    public class Solution {
        public int maxProfit(int[] prices) {
            int max = 0;
            for(int i = 0; i < prices.length-1; i++){
                for(int j = i; j < prices.length-1 ; j++){
                    if(prices[j+1] - prices[i]>max){
                        max = prices[j+1] - prices[i]; 
                    }
                }
            }
            return max;
        }
    }
    

      

  • 相关阅读:
    .NET 环境中使用RabbitMQ
    WPF窗口模板——Style样式
    C#获取当前日期时间
    C#解析JSON字符串总结
    c#简单加密和对称加密
    List<T>转换为二维数组
    java后台导出pdf
    C# 创建 读取 更新 XML文件
    python 第三天
    编写登录接口
  • 原文地址:https://www.cnblogs.com/xww115/p/11174019.html
Copyright © 2011-2022 走看看