LeetCode 121 Best Time to Buy and Sell Stock
来源:互联网 发布:金数据怎么用 编辑:程序博客网 时间:2024/05/18 00:43
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.
用一个数组A[n-1]来存储当天与前一天股票的差价,从而将该题转化为最大子序列和的问题,只不过没有负值,最小为0罢了。A[i]表示第i+1天股票价格与第i天的股票价格的差值。
public class Solution {public int maxsum(int [] num){int sum=0;int max=Integer.MIN_VALUE;for(int i=0;i<num.length;i++){sum+=num[i];if(max<sum) max=sum;if(sum<0) sum=0;}return max>0?max:0;} public int maxProfit(int[] prices) { if(prices.length==0||prices.length==1) return 0; int [] sub=new int [prices.length-1]; for(int i=0;i<sub.length;i++){ sub[i]=prices[i+1]-prices[i]; } return maxsum(sub); }}
0 0
- LeetCode 121: Best Time to Buy and Sell Stock
- LeetCode(121)Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- LeetCode: Best Time to Buy and Sell Stock [121]
- LeetCode 121 Best Time to Buy and Sell Stock
- [leetcode 121] Best Time to Buy and Sell Stock
- Leetcode NO.121 Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- LeetCode(121) Best Time to Buy and Sell Stock (Java)
- leetcode-121 Best Time to Buy and Sell Stock
- leetcode || 121、Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock - LeetCode 121
- leetcode#121 Best Time to Buy and Sell Stock
- Leetcode 121 Best Time to Buy and Sell Stock
- Leetcode #121 Best Time to Buy and Sell Stock
- leetcode 121: Best Time to Buy and Sell Stock
- leetcode: (121) Best Time to Buy and Sell Stock
- 121 Best Time to Buy and Sell Stock [Leetcode]
- C语言第三版课后习题答案
- JAVA私人总结
- C++学习笔记31,指向引用的指针(3)
- LeetCode 136 Single Number
- 在一堆很大的数中取出最小的前100个数
- LeetCode 121 Best Time to Buy and Sell Stock
- vim中的加密文件
- glusterfs文件系统性能测试
- from zhucheng大牛的poj题目分类
- 学位论文检测系统的说明与修改
- EGL接口介绍
- Mybatis like 模糊查询问题
- 缘
- POJ 2486 Apple Tree