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;
        }
    }
    

      

  • 相关阅读:
    Azkaban 简介(一)
    大数据平台搭建(Ambari +HDP)
    大数据平台比较-CDH、HDP、CDP
    Kylin 操作使用(六)
    Kylin 安装部署(五)
    Kylin 核心概念(四)
    数据流图
    android:sharedUserId
    Android的uid与UserHandle
    C++ 多态
  • 原文地址:https://www.cnblogs.com/xww115/p/11174019.html
Copyright © 2011-2022 走看看