Best Time to Buy and Sell Stock
来源:互联网 发布:dns劫持后的域名来路 编辑:程序博客网 时间:2024/04/26 01:37
Problem:
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.
Solution:
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null||prices.length==0)
return 0;
int cost = prices[0];
int profit = 0;
for(int i=0;i<prices.length;i++)
{
if(prices[i]-cost>profit)
profit = prices[i] - cost;
if(prices[i]<cost)
cost = prices[i];
}
return profit;
}
}
public int maxProfit(int[] prices) {
if(prices==null||prices.length==0)
return 0;
int cost = prices[0];
int profit = 0;
for(int i=0;i<prices.length;i++)
{
if(prices[i]-cost>profit)
profit = prices[i] - cost;
if(prices[i]<cost)
cost = prices[i];
}
return profit;
}
}
0 0
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- ubuntu 下eclipse 打不开
- Word Ladder
- 各种工业以太网比较(EtherCAT,EtherNet/IP,ProfiNet,Modbus-TCP,Powerlink)
- VMware上新建windows 10 虚拟机(1)
- Binary Tree Maximum Path Sum
- Best Time to Buy and Sell Stock
- 在cocos2dx中的点击事件
- Python模块学习 之zipfile zip文件操作
- 如何实现广度优先遍历(BFS)
- 求n个数的子集的三种思路
- hashCode()、equals()以及compareTo()方法的理解
- splash界面代码
- Codeforces Round #269 (Div. 2) B. MUH and Important Things
- sgu107:987654321 problem