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.

    [解题思路]

    记录一个最小值,每次拿当前值与最小值比较,如果两者差>profit,则更新profit

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int profit = 0, min = Integer.MAX_VALUE;
     6         for(int i = 0; i < prices.length; i++){
     7             if(prices[i] < min){
     8                 min = prices[i];
     9             }
    10             if(prices[i] - min > profit){
    11                 profit = prices[i] - min;
    12             }
    13         }
    14         return profit;
    15     }
    16 }
  • 相关阅读:
    12.22冲刺总结
    Android远程服务
    短信电话监听
    Android本地服务
    意图
    多线程下载
    异步HTTP请求
    提交数据到服务器
    通过HTTP访问网络资源
    观察者
  • 原文地址:https://www.cnblogs.com/feiling/p/3264470.html
Copyright © 2011-2022 走看看